Laravel5 series tutorial 8: queryScope and setAttribute

Source: Internet
Author: User
Laravel5 series tutorial 8: queryScope and setAttribute

From https://laravist.com/article/16

Laravist is the Laravel community I just launched. if you have any questions related to Laravel, please come here and ask me. I will try my best to solve the problem. later I will try to record some video tutorials, this is probably the form

Https://laravist.com/lesson/1

The usage of queryScope and setAttribute in laravel is as described in the previous section.

Application scenarios

The first thing I want to do here is to briefly talk about the application scenarios of these two knowledge points. we always want to be lazy during development, so we should consider the following two scenarios:

  • Data needs to be pre-processed when stored in the database. for example, a simple example is given: when we save the user's login password, the password must be encrypted in some way before being written to the database. do we encrypt the transmitted data every time after the form is submitted? Is there a mechanism to automatically encrypt the password before it is stored in the database? In this way, we don't have to worry about password encryption when processing the form.

  • Think about whether the data we are presenting to users is basically retrieved from the database? We usually have a lot of query statements. in this case, many query statements can be repeated. However, once multiple statements are repeated, basically, there will be optimization methods, so queryScope will be used in this case.

  • SetAttributes

    Previously, we set published_at to the date when the article was created:

    $input['published_at'] = Carbon::now();

    However, this is not what we want. we hope there is a way to control it, such as setting the article release date in the form. So, let's implement the following: first put the published_at field in our form, in create. blade. in php, add the published_at input box and enter:

    {!! Form: label ('Ed Hed _ at', 'publication date ')!!} {!! Form: input ('date', 'hhed _ at', date ('Y-m-D '), ['class' => 'form-control'])!}

    This code is added after textarea and the Form: input () method is used here, because the Form class does not have a method similar to Form: date () to specify date, therefore, we use Form: input () and specify the input type as date, and use date ('Y-m-D') to specify the default value as the day when the article is published, but we can modify it to see what our page is like:

    Here we can see that we have obtained the published_at field. at this time, you can modify the code of the store () method in ArticleController:

    $input = $request->all();$input['intro'] = mb_substr($request->get('content'),0,64);Article::create($input);return redirect('/');

    We deleted the $ input ['hhed _ at'] = Carbon: now (); line of code, and then tried to create an article to see it:

    OK. here, the article can be created successfully, but if we look at the data in the database:

    The date format here is not the ideal mode. Is there a way to set it to the same as created_at and updated_at? What do I know about time, minute, and second? You can use setAttribute to complete this process. add the following method to Article. php:

    public function setPublishedAtAttribute($date){    $this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d',$date);}

    Note that this method is set + field name + Attribute, and the Hump method is also used. For example, when you want to encrypt the password, you can:

    Public function setpasswordattrird ($ passowrd) {$ this-> attributes ['password'] = Hash: make ($ passowrd); // just an example}

    Here we use the Carbon class, because we also want to process the published_at field as a Carbon object, which will be of great benefit in the future. Use Carbon \ Carbon; in the file header to introduce Carbon. At this time, we will post it again:

    Let's take a look at the database:

    If the format is correct, add a line of code for Article. php to use published_at as the Carbon object for processing:

    protected $dates = ['published_at'];

    This is done. we will discuss more about the benefits and features of Carbon later.

    QueryScope

    The above implementation uses published_at to implement the article release date, but the current article display is still the original style, this is not the result we want, because we have just set the posting date to 9-12 (9-08 when writing an article), we have to restrict it. First, we can directly implement the query. for example, we can write the query statement in the index () method of ArticleController as follows:

    $articles = Article::where('published_at','<=',Carbon::now())->latest()->get();

    We can use where () to directly limit the display of articles with the published_at time less than or equal to the current time to see the effect:

    I found that the articles published in the future are indeed hidden. This seems to have achieved the goal. why should I introduce the qeuryScope usage? This is because code reusability is taken into account. for example, if we use Article: where ('hhed _ at', '<=', Carbon: now () in multiple places ()) is there a way to write a query statement in the following format?

    $articles = Article::latest()->published()->get();

    Instead of where ('hhed _ at', '<=', Carbon: now, this makes the code more readable.

    So let's talk about the usage of queryScope. think about the purpose of setting the published_at field before:

    We hope that we can manage the articles in a simple way. for example, when we write a series of articles, we may write several articles a day. but in this case, we can just send an article, digest an article every day is very good, so as the author, I don't want to show it to users before the release date. However, I want to save it to the database after I write an article, so that it will be automatically displayed on the release date. So we can take advantage of the published_at field.

    Add the following method to our Article. php:

    public function scopePublished($query){    $query->where('published_at','<=',Carbon::now());}

    Note that the name of the scope + custom method is the same as the camper method. For example, to use published (), we define it as scopePublished ($ query ). In this case, you can actually use the query described above. in the index () method of ArticleController:

    $articles = Article::latest()->published()->get();

    Let's look at the effect again. I believe you will refresh it again.

    Summary

    Finally, we will briefly introduce the usage of queryScope and setAttribute. The next section will introduce an important content of Eloquent: Eloquent Relationship. At that time, laravel will become more and more powerful.

    Finally:Happy Hacking

    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.