What are Mutators and Accessors in Laravel

北慕城南 提交于 2021-02-07 19:27:47

问题


I am trying to understand accessors & mutators and why I need them. And my another ask is the middle part of an attribute's method for an example:

Accessor:

public function getFirstNameAttribute($value)
{
   return ucfirst($value);
}

Mutator:

public function setFirstNameAttribute($value)
{
    $this->attributes['first_name'] = strtolower($value);
}

Here, we can see getFirstNameAttribute and setFirstNameAttribute methods and I haven't been able to clear the middle part FirstName of them. I will really be grateful for a better explanation and kind cooperation.


回答1:


Accessors create a "fake" attribute on the object which you can access as if it were a database column. So if your person has first_name and last_name attributes, you could write:

public function getFullNameAttribute()
{
  return $this->first_name . " " . $this->last_name;
}

Then you can call $user->full_name and it will return the accessor. It converts the function name into a snake_case attribute, so getFooBarBazAttribute function would be accessible through $user->foo_bar_baz.

Mutator is a way to change data when it is set, so if you want all your emails in your database to be lowercase only, you could do:

public function setEmailAttribute($value)
{
  $this->attributes['email'] = strtolower($value);
}

Then if you did $user->email = "EMAIL@GMAIL.com"; $user->save(); in the database it would set email@gmail.com




回答2:


From the docs accessor and mutator both are public function in Laravel model for getting and setting model's attributes

An accessor will automatically be called by Eloquent when attempting to retrieve the value of the first_name attribute:

$fullName = $user->full_name;

It's for customizing a model's attributes or adding fake attributes

On the other hand mutator is for setting a real attribute of a model

Mutator will be automatically called when we attempt to set the value of the an attribute



来源:https://stackoverflow.com/questions/49969855/what-are-mutators-and-accessors-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!