Laravel 4更新鼻涕虫


Laravel 4 update slug

我有它,这样当创建一个新分支时,名称就会变成一个slug进行查找,但当我更新记录时,slug变量保持不变,有没有办法让它在记录更改时自动更新?

class Branch extends 'Eloquent {
    public static $rules = [
        'name' => 'required'
    ];
    protected $fillable = ['name', 'slug'];
    protected function setNameAttribute($name)
    {
        $this->attributes['name'] = $name;
        $this->attributes['slug'] = Str::slug($name);
    }
}

在我的控制器里。。。

public function update($slug)
{
    $branch = Branch::whereSlug($slug);
    $validator = Validator::make($data = Input::except('_method', '_token'), Branch::$rules);
    if ($validator->fails())
    {
        return Redirect::back()->withErrors($validator)->withInput();
    }
    $branch->update($data);
    return Redirect::route('branches.index');
}

首先,如果您要处理的是Eloquent模型,那么模型事件应该会进入赋值函数,而Fluent查询生成器不会。我认为Branch::whereSlug($slug)返回一个Fluent查询生成器-只需检查Branch::whereSlug($slug)->firstOrFail()是否工作即可。我想可能会的。


如果做不到这一点,我建议有两种选择——首先,Colin Viebrock有一个非常好用的生成蛞蝓的软件包。

如果你更喜欢自制它,我会使用一个模型事件将它放在boot方法中:

public static function boot() {
    static::saving( function( $model ) {
        $model->name = $model->name; // force the slug to be rebuilt
    } );
}