Laravel 5 Series Tutorial Eight: Queryscope and SetAttribute

Source: Internet
Author: User

Original from HTTPS://LARAVIST.COM/ARTICLE/16

Laravist is my just on-line laravel community, there are any issues related to Laravel can come here to ask me, I will try to help you solve the problem, later will try to record some video tutorials, the form is probably like this

Https://laravist.com/lesson/1

Just as we said in the previous section, let's talk about the use of Queryscope and setattribute in Laravel.

About the application scenario

First of all, I want to tell you a little bit about the application scenarios of these two knowledge points, we always want to have a lazy way in development, so consider these two scenarios:

  • Data in the database to be pre-processing, such as consider a simple example: when we save the user's login password, we need to encrypt the password in some way after the write to the database, we do every time after the submission of the table slip to the data transmitted over the data encryption once? Can there be a mechanism that automatically completes the encryption of passwords before they are put into storage? So we don't have to worry about password encryption when we're working on the form.

  • Think about whether the data we're showing to users is basically taken from the database? So often we will have a lot of query statements, in this case a lot of query statements can be repeated, but in the line of writing code, once there are multiple repetitions, there will basically be an optimization method exists, so this time queryscope will come in handy

  • SetAttributes

    Previously, we were setting published_at as the date the article was created:

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

    However, this is not what we want, we want to have a controllable way, such as to set the release date of the article in the form, so let's implement this: first put published_at this field in our form, In create.blade.php, add the Published_at input box to enter:

    {!! Form::label (' Published_at ', ' release date ')!! {!! Form::input (' Date ', ' Published_at ', date (' y-m-d '), [' class ' = ' Form-control '])!

    This piece of code is added to textarea, which uses the Form::input () method, because the form does not have a form like this::d ate () specifies the date method, so we use Form::input () and specify the type of input as date, and use Date (' y-m-d ') to specify the default value for the day the article was published, but we can modify it, let's see what our page is now:

    Here we can see that we have published_at this field, this time, you can modify the Articlecontroller in the store () method code:

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

    We removed $input[' published_at '] = Carbon::now (); This line of code, and then try to create an article to see:

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

    The date set here is not the ideal pattern, is there a way to set it to be the same as Created_at and Updated_at? What do you know when you're a minute or seconds? This time you can use SetAttribute to complete, add the following method in the article.php:

    Public Function Setpublishedatattribute ($date) {    $this->attributes[' published_at ') = Carbon:: Createfromformat (' y-m-d ', $date);}

    Note here that this is set+ field name +attribute, and there is the use of hump method. For example, when you want to encrypt the password, you can:

    Public Function Setpasswordattribute ($PASSOWRD) {    $this->attributes[' password ') = Hash::make ($PASSOWRD);    Just an example}

    Here we use the carbon class, because we also want to treat the Published_at field as a carbon object, which can be of great benefit later on. Note Using use Carbon\carbon at the head of the file, to introduce Carbon. This time we will publish it again:

    Take a look at the database:

    So the format is right, then add a line of code for article.php so that Published_at is handled as a carbon object:

    protected $dates = [' published_at '];

    For this to be done, for more carbon benefits and usage features, we'll talk about it later.

    Queryscope

    The above implementation of the article with PUBLISHED_AT implementation of the release date, but now the article is still the original style, this is not the result we want, because we have just set the publication date of 9-12 of the article (9-08 when writing the article) is also shown, we have to limit. First we can do this directly at the time of the query, such as in the Index () method of Articlecontroller, which writes the query statement:

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

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

    Found in the next time published articles are indeed hidden, so it seems to have achieved the purpose, why also introduce qeuryscope this usage? This is because of the reusability of the code, for example, if we use multiple places to Article::where (' published_at ', ' <= ', Carbon::now ()) This condition is limited, Do we have a way to write query statements like this?

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

    is to use published () as a custom method instead of where (' published_at ', ' <= ', Carbon::now ()), which makes the code more readable.

    So let's just say, Queryscope's usage, think about the purpose of our previous setting published_at this field:

    We want to be able to simply manage the article, for example, we write a series of articles, it is possible to write a few times a day, but this time in fact we send an article is good, every day digest an article is very good, so as the author, I do not want to publish the date of the article will show to the user to see, but, I wrote the article also want to put it into the database, let it appear on the date of the release automatically, so good. So, we can make good use of published_at this field

    Add the following method to our article.php:

    Public Function scopepublished ($query) {    $query->where (' published_at ', ' <= ', Carbon::now ())}

    Note Here the method name of the way of writing scope+ custom, and also is the Hump method as always. For example, we want to use the published () method, which is defined as scopepublished ($query). This time you can really use the above query, in the Articlecontroller Index () method:

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

    Again to see the effect, I believe you refreshed after the same.

    Summarize

    Again the final end, here we briefly introduced the use of Queryscope and setattribute, the next section intends to say eloquent an important content: eloquent relationship. At that time will be more and more feel laravel strong.

    Last: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.