_php basics of accessor for laravel learning tutorials

Source: Internet
Author: User
Tags dateformat datetime php web development

Objective

Laravel is a simple, elegant PHP Web development framework that frees developers from spaghetti code and develops great web apps with simple, elegant, expressive syntax, followed by a small weave to learn the accessors of Laravel.

Eloquent: Introduction to accessors

Accessors and memory allow you to format an eloquent model property when it is obtained or set. For example, you might want to encrypt a value before it is stored in a database laravel encrypter , and you can automatically decrypt the property when you access it through the model.

In addition to customizable accessors and storage,eloquent can automatically convert a date field to a Carbon instance , or even convert a string field to JSON.

Accessors & Accessors

Define an accessor

To define an accessor, you need to create a method on your model getFooAttribute , which is named for the hump of the Foo name of the column you need to access. In this example, we will define an first_name accessor for a property. This accessor is triggered when eloquent tries to get the first_name property value:

<?php

namespace App;

Use Illuminate\database\eloquent\model;

Class User extends Model
{
 /**
  * Get the User ' s name.
  * *
  @param string $value
  * @return string
 /Public Function Getfirstnameattribute ($value)
 { Return
  Ucfirst ($value);
 }

As you can see, the original value of the attribute is passed to the accessor, which allows you to manipulate the original value and return the formatted value. You first_name can access the value from the accessor simply by accessing the property in a simple access attribute:

$user = App\user::find (1);

$firstName = $user->first_name;

Define a memory

To define a memory, you need to define a method on your model setFooAttribute , which is the Foo name of the hump style of the column you want to access. So, this time, let's first_name define a memory for the attribute. This memory is invoked when the model attempts to set first_name the value of a property:

<?php

namespace App;

Use Illuminate\database\eloquent\model;

Class User extends Model
{
 /**
  * Set The user ' s name.
  * *
  @param string $value
  * @return string
 /Public Function Setfirstnameattribute ($value)
 {
  $this->attributes[' first_name '] = Strtolower ($value);
 }

The memory receives the value that is about to be set to the property, which allows you to manipulate the value and set it to the properties within the model $attributes . So, for example, if we try to first_name set the property to Sally :

$user = App\user::find (1);

$user->first_name = ' Sally ';


In this example, the setFirstNameAttribute method is invoked and accompanied by a Sally value. The memory applies the strtolower method to lowercase the name and then sets the value to $attributes an internal array.

Date accessor

The default is to Eloquent convert created_at and updated_at column Carbon instances, which can provide a variety of useful methods, and it inherits from native PHP DataTime classes.

You can customize which fields can be automatically converted, or even completely disable the conversion, and you need to make a copy of the attribute in your model $dates :

<?php

namespace App;

Use Illuminate\database\eloquent\model;

Class User extends Model
{
 /**
  * The attributes that should is mutated to dates
  *
  * @var Array
   */
 protected $dates = [' Created_at ', ' updated_at ', ' deleted_at '];

When a column is considered a date, you can set it as a UNIX timestamp, a date string ( Y-m-d ), a time string, and an DateTime / Carbon instance, and the value of the date is automatically stored correctly in the database:

$user = App\user::find (1);

$user->deleted_at = Carbon::now ();

$user->save ();

As mentioned above, when the acquired property is one of $dates the values listed by the attribute, it is automatically converted to an Carbon instance, which allows you to use Carbon some of the methods on the attribute:

$user = App\user::find (1);

return $user->deleted_at->gettimestamp ();


Default, the timestamp is formatted Y-m-d H:i:s as a format. If you want to customize the timestamp format, you need to set the properties in your model $dateFormat . This property determines how the date property is stored in the database and how it is displayed when the model is serialized or JSON serialized:

<?php

namespace App;

Use Illuminate\database\eloquent\model;

Class Flight extends model
{
 /**
  * The storage format of the model ' s date columns.
  *
  * @var string
 /protected $dateFormat = ' U ';
}

Property conversions

You can define attributes in your model $casts to provide a convenient way to convert a property to a generic data type. The $casts property should be an array, and the key for each item should be the name of the property that needs to be converted, and the value of the key should be the type you want the property to be converted to. The types of conversions supported are:,,,,,,,,,,, integer real float double string boolean object array coolection date datetime and timestamp .

For example, let's convert the is_admin attribute, which stores the value in the database as an integer (0 or 1), and we convert it to a Boolean value:

<?php

namespace App;

Use Illuminate\database\eloquent\model;

Class User extends Model
{
 /**
  * The attributes that should is casted to native types.
  *
  * @var array
 /protected $casts = [
  ' Is_admin ' => ' Boolean ',
 ];
}

Now, whenever you access a is_admin property, its value is converted to a Boolean value, even if it stores an integer value in the database:

$user = App\user::find (1);

if ($user->is_admin) {
 //
}

Array conversions

arrayThe type of conversion is especially useful for storing columns that serialize JSON values. For example, if the database has a field of type TEXT and it stores serialized JSON, if you add the conversion of the attribute, array it will automatically deserialize to the PHP array when you access the property on the eloquent model:

<?php

namespace App;

Use Illuminate\database\eloquent\model;

Class User extends Model
{
 /**
  * The attributes that should is casted to native types.
  *
  * @var array
 /protected $casts = [
  ' Options ' => ' array '
 ];
}

When you escape the definition, you can access the options attribute, and it is automatically deserialized from JSON to the PHP array. When you set the value to the options attribute, the given array is automatically serialized into JSON format and stored:

$user = App\user::find (1);

$options = $user->options;

$options [' key '] = ' value ';

$user->options = $options;

$user->save ();

The above is a small series for everyone to organize the Laravel Learning Tutorial of the full contents of the accessor, there is a need for small partners can refer to learning, small series will also update laravel related knowledge, please continue to pay attention to cloud habitat community.

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.