Laravel Tutorial Eight: Queryscope and SetAttribute

Source: Internet
Author: User
Tags laravel tutorial

Laravel Tutorial Eight: Queryscope and SetAttribute

This article is original article, without consent, prohibit reprint.

    • Laravel
    • Eloquent
    • Database

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:

    1. 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.
    2. 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 published_at put this field in our form, in create.blade.php , add published_at input Box input:

<div class="form-group">{!! Form::label(‘published_at‘,‘发布日期‘) !!}{!! Form::input(‘date‘,‘published_at‘,date(‘Y-m-d‘),[‘class‘=>‘form-control‘]) !!}</div>

This piece of code is added to the textarea, which is used here, Form::input() because the form does not have a Form::date() method like the specified date, so we use Form::input() and specify input the type date , and use date(‘Y-m-d‘) the To specify the default value for the article on the day of posting, but we can modify it and we'll look at what our page is now like:

Here we can see that we have published_at this field, this time, you can modify the ArticleController method in the store() 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 tried to create an article to look at:

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 format, is there a way to set it to be created_at updated_at the same as the same? What do you know when you're a minute or seconds? This time you can use the setattribute to complete, Article.php add the following method in:

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

This set+字段名+Attribute is the way to look at it, and some of it is to use hump. For example, when you want to encrypt the password, you can:

public function setPasswordAttribute($passowrd){ $this->attributes[‘password‘] = Hash::make($passowrd); //仅仅是举例}

Here we use the carbon class, because we also want to published_at treat the field as a carbon object, which will have great benefits later on. Note the use of the file header use Carbon\Carbon; to introduce carbon. This time we will publish it again:

Take a look at the database:

In this way, the format is the right one, so you can do it Article.php as a carbon object to add a line of code published_at :

protected $dates = [‘published_at‘];

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

Queryscope

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

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

We use where() published_at articles that have a direct limit of time less than or equal to the current time to display and 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 Article::where(‘published_at‘,‘<=‘,Carbon::now()) this conditional limit in multiple places, do we have a way to write query statements like this one?

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

is simply published() to use this custom method instead, which makes the where(‘published_at‘,‘<=‘,Carbon::now()) code more readable.

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

我们希望可以对文章进行简单地管理,比如我们在写系列文章的时候,有可能一天写了好几篇,但是这种时候其实我们发一篇文章就好了,每天消化一篇文章就很不错了,所以作为作者,我并不想还没到发布日期的文章就展示给用户看,但是,我写了文章也想把它存入数据库,让它在该发布的日期自动显示,这样就好了。于是,我们可以好好利用一下published_at这个字段

Article.phpAdd the following method to our list:

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

Here to note the wording scope+自定义的方法名字 , there is always the Hump method. For example, if we want to use published() this method, we define it as scopePublished($query) . This time you can really use the above query, in ArticleController the 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

Laravel Tutorial Eight: Queryscope and SetAttribute

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.