QueryScope and setAttribute usage

Source: Internet
Author: User
Tags dateformat
QueryScope and setAttribute usage setAttribute

Create a date in the form and then process it directly, instead of writing the time in the controller.

App/Http/Controllers/ArticlesController. php public function store (Request $ requests) {$ input = Request: $ requests-> all (); $ input ['Publish _ at'] = Carbon :: now (); // It turns out that Articles are written through the hard write time: create ($ input); return redirect ('/articles ');}

Change the processing time in the form

App/Http/Controllers/ArticlesController. php public function store (Request $ requests) {// cancel the hard write time now Articles: create ($ requests-> all ()); return redirect ('/articles ');}

(Form)

Resources/views/articles/create. blade. php @ extends ('layout. app') @ section ('content') create an article {!! Form: open (['URL' => '/articles/store'])!}
     

{!! Form: label ('title', 'Title :')!!} {!! Form: text ('title', null, ['class' => 'form-control'])!}

{!! Form: label ('content', 'content :')!!} {!! Form: textarea ('content', null, ['class' => 'form-control'])!}

{!! Form: label ('Publish _ at', 'publish _ :')!!} {!! Form: date ('Publish _ at', date ('Y-m-D'), ['class' => 'form-control'])!} // Write time here, which is selected by the user

{!! Form: submit ('post analytics', ['class' => 'btn btn-primary form-control'])!} {!! Form: close ()!!} @ Stop

Information displayed in the database

Id title content publish_at created_at updated_at5 I am a new article Hello, 00:00:00 07:32:48 07:32:48 // the time here is only date, but there is no time

Therefore, a solution is provided to write a method in the model and associate the model with the database to convert the time format when writing data to the database (likewise, it can identify the processing of other data)

This is the setAttribute usage.

Write in the model and write an automatically processed function setattribute.

App/Articles. phpclass Articles extends Model {protected $ fillable = ['title', 'content', 'publish _ at']; public function setPublishAtAttribute ($ date) // set + field name + attribute, laravel automatically determines the field name, and the name must follow the hump naming method {$ this-> attributes ['Publish _ at'] = Carbon :: createFromFormat ('Y-m-D', $ date); // call the attributes method of the model to set }}

The database can see that the data has been generated and the time is sometimes divided.

Id title content publish_at created_at updated_at6 I love the second article 08:17:29 08:17:29

The original setattribute is called setattribute, but it also supports inserting a field in the middle. the conversion process can also be seen in the debug process.

In Carbon. php line syntax at Carbon: createFromFormat ('Y-n-j G: I: S', 'Y-m-d-2016-05-27-21 8:21:00 ', null) in Carbon. php line Upload at Carbon: create ('Y-m-D', '2017-05-27 ', null) in Carbon. php line 383at Carbon: createFromDate ('Y-m-D', '2017-05-27 ') in Articles. php line 14 at Articles-> setPublishAtAttribute ('1970-05-27 ') in Model. php line 2860 // call setPublishAtAttributeat Model-> setAttribute ('Publish _ at', '2017-05-27 ') in Model. php line 447 // here it is converted into setAttributeat Model-> fill (array ('_ token' => '', 'title' =>' I am the second article ', 'content' => 'love', 'publish _ at' => '2017-05-27 ') in Model. php line 281at Model->__ construct (array ('_ token' => '', 'title' =>' I am the second article ', 'content' => 'love', 'publish _ at' => '2017-05-27 ') in Model. php line break at Model: create (array ('_ token' => '', 'title' =>' I am the second article ', 'content' => 'love', 'publish _ at' => '2017-05-27 ') in ArticlesController. php line 31at ArticlesController-> store (object (Request ))
Queryscope

Modify the hard-coded method in the controller's processing time

App/Http/Controllers/ArticlesController. php public function index () {$ articles = Articles: latest ()-> where ('Publish _ at', '> =', Carbon: now ()) -> get (); // return view ('Articles. index', compact ('Articles '));}

Changed:

Public function index () {// $ articles = Articles: latest ()-> where ('Publish _ at', '<=', Carbon: now ()) -> get (); $ articles = Articles: latest ()-> publish ()-> get (); // create a new method, the purpose is to be more flexible and make the current code more concise and easy to understand, // for example, here we get the last piece of data from articles, filter the publish time, and get the approximate meaning of the final data. we don't need to look at the return view ('Articles. index', compact ('Articles '));}

Then add the scope in model articles.

App/Articles. php public function scopePublish ($ query) {// scope syntax restriction, scope + the name of the publish function just now (name by camping) $ query-> where ('Publish _ ', '<=', Carbon: now (); // it is fixed to pass in a $ query. a temporary understanding is a data query result, and then use where to filter data}

Because the model articles instance is used, the scope name will allow laravel to execute some automatic data queries, so it can pass in and process the data query result $ query.

Popular science knowledge:

Latest () returns a builder object.

Builder|Builder latest(string $column = 'created_at')Add an "order by" clause for a timestamp to the query.Parametersstring  $column Return ValueBuilder|Builder

A builder object is a special data object and an object for laravel database management. a builder contains a lot of data information for easy and direct use.

The 'all' method returns a collection object.

static Collection|Model[] all(array|mixed $columns = array('*'))Get all of the models from the database.Parametersarray|mixed $columns    Return ValueCollection|Model[]

This is the collection format:

Collection {#136 items # items: array: 6 [items 0 => Articles {#137 items # fillable: array: 3 [] # connection: null # table: null # primaryKey: "id" # perPage: 15 + incrementing: true + timestamps: true # attributes: array: 6 [author "id" => 6 "title" => "I am the second article" "content" => "h_" "publish_at" => "08:17:29 "" created_at "=>" 08:17:29 "// The data in the collection is an array containing objects, so it is convenient to call. "Updated_at" => "2016-05-21 08:17:29"] # original: array: 6 [] # relations: [] # hidden: [] # visible: [] # appends: [] # guarded: array: 1 [] # dates: [] # dateFormat: null # casts: [] # touches: [] # observables: [] #: [] # morphClass: null + exists: true + wasRecentlyCreated: false} 1 => Articles {#138} 2 => Articles {#139} 3 => Articles {#140} 4 => Articles {#141} 5 => Articles {# 142}]}

This is the builder format:

Builder {#128 items # query: Builder {#127 items # connection: MySqlConnection {#123} # grammar: MySqlGrammar {#124} # processor: MySqlProcessor {#125} # bindings: array: 6 [] + aggregate: null + columns: null + distinct: false + from: "articles" + joins: null + wheres: array: 1 [the data contained in pipeline // builder will exist here, but it cannot be used directly. you need to use methods like get to convert data. 0 => array: 5 [principal "type" => "Basic" "column" => "publish_at" "operator" => "> =" "value" => Carbon {#129 principal +" date ": "09:08:10. 000000 "+" timezone_type ": 3 +" timezone ":" UTC "}" boolean "=>" and "] + groups: null + havings: null + orders: array: 1 [] + limit: null + offset: null + unions: null + unionLimit: null + unionOffset: null + unionOrders: null + lock: null # backups: [] # bindingBackups: [] # operators: array: 26 [] # useWritePdo: false} # model: Articles {#121 rules # fillable: array: 3 [] # connection: null # table: null # primaryKey: "id" # perPage: 15 + incrementing: true + timestamps: true # attributes: [] # original: [] # relations: [] # hidden: [] # visible: [] # appends: [] # guarded: array: 1 [] # dates: [] # dateFormat: null # casts: [] # touches: [] # observables: [] # with: [] # morphClass: null + exists: false + wasRecentlyCreated: false} # eagerLoad: [] # macros: [] # onDelete: null # passthru: array: 11 [] # scopes: []}

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.