Laraverl Eloquent query scope and model events

Source: Internet
Author: User
Tags foreach

1. Query scope

Eloquent also supports encapsulating some common queries into model methods for convenient calling. We call it "query scope". It is very simple to implement the query scope, you only need to add the scope prefix before the model method. For example, if we often need to obtain the articles with the highest number of views, we can use this mechanism to implement -- define a scopePopular method in Post:

Public function scopePopular ($ query)
{
Return $ query-> where ('Views ','> = ', 100 );
}

Correspondingly, we define the test code in the controller as follows:

$ Posts = Post: popular ()-> orderBy ('View', 'desc')-> get ();
Foreach ($ posts as $ post ){
Echo '& lt;'. $ post-> title. '& gt;'. $ post-> views. 'Views <br> ';
}

Access the http://laravel.app: 8000/test in a browser and the output is as follows:

<Test 3> 800 views
<Test 2> 500 views
<Test 1 title> 100 views

In addition, the query scope also supports dynamic input parameters. To test this method, we add a status field for posts:

Add the status field to the posts table

At the same time, add a new scopeStatus method in the model class:

Public function scopeStatus ($ query, $ status = 1)
{
Return $ query-> where ('status', $ status );
}

Next, we will test this method:

$ Posts = Post: popular ()-> status (1)-> orderBy ('View', 'desc')-> get ();
Foreach ($ posts as $ post ){
Echo '& lt;'. $ post-> title. '& gt;'. $ post-> views. 'Views <br> ';
}

The output is as follows:

<Test 3> 800 views
<Test 2> 500 views

2. Model events

Eloquent also supports model events-events are triggered when a model is created, updated, or deleted. Currently, Eloquent supports eight types of events: creating, created, updating, updated, saving, saved, deleting, and deleted.

Deleting and deleted are easy to understand. This is triggered when the model is deleted. deleting is executed before the delete operation and deleted is executed after the model is deleted.

When a model is created, saving, creating, created, and saved are executed in sequence. Similarly, saving, updating, updated, and saved are executed in sequence during model update. Whether you use create/update or directly call the save method, the corresponding event is triggered (provided that the corresponding model event is registered ).

You can register a model event wherever you like. Here we choose to register it in the boot method of AppServiceProvider of the service provider:

Post: saving (function ($ post ){
Echo 'Saving event is fired <br> ';
});

Post: creating (function ($ post ){
Echo 'creating event is fired <br> ';
});

Post: created (function ($ post ){
Echo 'created event is fired <br> ';
});

Post: saved (function ($ post ){
Echo 'saved event is fired <br> ';
});

Then write the test code in the controller as follows:

$ Data = array (
'Title' => 'test model event ',
'Content' => 'test content ',
'Cat _ id' => 1,
);
$ Post = Post: create ($ data );
If (! $ Post-> exists ){
Echo 'failed to add the article! '; Exit ();
}
Echo '& lt;'. $ post-> title. '& gt; saved successfully! ';


Next, access the http://laravel.app: 8000/test in browsing, and enter the following on the page:

Saving event is fired
Creating event is fired
Created event is fired
Saved event is fired
<Test model event>

Saved successfully!

Note that if the saving/creating/updating/deleting event returns false, the creation, update, and deletion operations will exit and will not be executed, for example, we modify the above creating event code as follows:

Post: creating (function ($ post ){
Echo 'creating event is fired <br> ';
If ($ post-> cat_id = 1)
Return false;
});

That is, when the article Category id is equal to 1, no longer execute, access the http://laravel.app again in the browser: 8000/test, the page output is as follows:

Saving event is fired
Creating event is fired

An error occurred while adding the article!
With model events, we can easily add corresponding business logic in different lifecycle stages of model creation, update, or deletion.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.