Tự học Laravel: (12) ELOQUENT ACCESSOR AND MUTATOR

Eloquent offers a convenient way to change its content when setting and getting model attributes. The methods for converting this attribute content are called accessors and mutators.

ACCESSOR

The method name is set to get attribute name Attribute(). Note that attribute names need to be described in camel-case, even if table field names are named in snake-case.

class Article extends Model
{
    ...
 
    public function getTitleAttribute($value)
    {
        return mb_strtoupper($value);
    }
 
}

MUTATOR

The method name is set attribute name Attribute().

class Article extends Model
{
    ...
 
    public function setTitleAttribute($value)
    {
        $this->attributes['title'] = mb_strtolower($value);
    }
 
}

https://laravel.com/docs/master/eloquent-mutators


DATE MUTATOR

Elocuent has a date mutator by default, and the created_at and updated_at attributes are converted to PHP’s DateTime extended Carbon instance. To tell Eloquent which attributes use a date mutator, add the attribute names to the dates array.

class Article extends Model
{
    ...

    protected $dates = ['published_at'];
 
    ...
}

https://laravel.com/docs/master/eloquent-mutators#date-mutators

Before specifying published_at as a date mutator

>>> $article = App\Article::first();
>>> $article->published_at
=> "2015-02-24 10:22:54" 
>>>
>>> $article->published_at = "2015-02-24 11:00:00"
=> "2015-02-24 11:00:00"
>>> $article->published_at
=> "2015-02-24 11:00:00" 
>>> exit

After specifying published_at as a date mutator

>>> $article = App\Article::first();
>>> $article->published_at
=> Illuminate\Support\Carbon @1535126513 {#2866
     date: 2018-08-25 01:01:53.0 Asia/Tokyo (+09:00),
   } 
>>>
>>> $article->published_at = "2018-08-25 12:00:00"
=> "2018-08-25 12:00:00"
>>> $article->published_at
=> Illuminate\Support\Carbon @1535166000 {#2856
     date: 2018-08-25 12:00:00.0 Asia/Tokyo (+09:00),
   }  
>>> 

Please refer to the following site about Carbon. You can also find Japanese information by searching on “PHP Carbon”.

http://carbon.nesbot.com/ 
https://github.com/briannesbitt/Carbon

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.