您现在的位置是:网站首页 > 心得笔记
laravel中Eloquent: 访问器、修改器
简介当你在 Eloquent 模型实例中获取或设置某些属性值的时候,访问器和修改器允许你对 Eloquent 属性值进行格式化。例如,新增用户时,插入库中的用户密码加密操作,就可以在访问器、修改器中完成操作
一、使用背景
今天在开发项目过程中,在完成新增用户时,把form表单传来的密码加密,在之前的操作中,我都直接在控制器中:
$password = md5($createRequest->input('password',''));二、访问器
但是,前两天刚看了laravel文档中关于模型访问器和修改器的介绍,于是在这里,我决定使用访问器完成如下操作:
1、先在模型中定义访问器
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
protected $id = 'id';
protected $fillable = ['name','password','created_at','updated_at'];
//定义密码访问器(MD5加密)
public function getPasswordAttribute($value)
{
return md5($value);
}
}注意:若要定义一个访问器,则须在你的模型上创建一个 getFieldAttribute 方法。要访问的 Field字段需使用「驼峰式」来命名。在上面这个例子中,我们将为 password 属性定义一个访问器。当 Eloquent 尝试获取 password 的值时,将会自动调用此访问器!
2、在控制器中使用访问器
在上面定义访问器可知,字段的原始值被传递到访问器中(在我的例子中是form表单传递的password值被传递到访问器中),允许你对它进行处理并返回结果(我这里是对传入的密码进行MD5加密操作)。如果想获取被修改后的值,你可以在模型实例上访问 password 属性:
$password = $user->password;
这时候获取的值就是加密后的密码了!
三、修改器
修改器,基本上与访问器要实现的效果无异。下面我再次拿上面那个例子说明:
public function store (Request $request,User $user)
{
$user->password = '123456';//本来form表单传来的passport='123456@a',我在程序中手动的将值设置为'123456' 注意:这里不管是否再次修改传来的值,在这里都要接收!
$user->fill($data)->save();
return redirect('/admin/user/index');
}1、定义修改器
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
protected $id = 'id';
protected $fillable = ['name','password','created_at','updated_at'];
//定义修改器
public function setPasswordAttribute($value)
{
$this->attributes['password'] = md5($value);//注意,这里直接获取属性已经被设置的值('123456'),允许你操作该值(MD5加密)并将其设置到 Eloquent 模型内部的 $attributes 属性上
}
}2、使用效果
//如果模型中没有定义修改器
dump($user);
//结果如下:
User{#266 ▼
#table: "users"
#id: "id"
#fillable: array:11 [▶]
#connection: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: array:1 [▼
"password" => "123456" ]
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]}
//如果定义了修改器
dump($user);
//结果如下:
User{#266 ▼
#table: "users"
#id: "id"
#fillable: array:11 [▶]
#connection: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: array:1 [▼
"password" => "e10adc3949ba59abbe56e057f20f883e" ]
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]}修改器的实际使用:
//控制器
public function store(Tpl $tpl, Request $request)
{
$tpl->fill($request->all())->save();
return redirect()->back()->with('flash_message', '保存成功!');
}
//model
<?php
namespace App\Models\Admin;
use Illuminate\Database\Eloquent\Model;
class Tpl extends Model
{
protected $id = 'id';
protected $table = 'tpl';
public $timestamps = true;
protected $fillable = ['type_id','month','plan_name','plan_img','plan_url','plan_content','plan_tips','downloads','status','type_fid','code'];
public function setMonthAttribute($value)
{
$this->attributes['month'] = join(',', $value);
}
public function setPlanContentAttribute($value)
{
$this->attributes['plan_content'] = htmlspecialchars(trim($value,''));
}
public function setPlanTipsAttribute($value)
{
$this->attributes['plan_tips'] = htmlspecialchars(trim($value,''));
}
}