【发布时间】:2015-08-15 10:47:48
【问题描述】:
我正在尝试在 this wondefull website 的帮助下学习 laravel 5。 对于我的活动模型,我想在将其保存到数据库之前生成 slug,因此我创建了以下模型。
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Activity extends Model {
protected $table = 'activitys';
protected $fillable = [
'title',
'text',
'subtitle'
];
// Here I want to auto generate slug based on the title
public function setSlugAttribute(){
$this->attributes['slug'] = str_slug($this->title , "-");
}
//
}
但是当我在 Activity 模型 slug 未填充的帮助下保存对象时,我尝试将其更改为 $this->attributes['title'] = "test" 进行测试,但它没有运行。我也尝试将参数 $title, $slug 添加到 setSlugAttribute() 但它没有帮助。
我做错了什么,有人可以解释在 setSomeAttribute($whyParameterHere) 的一些示例中使用的参数。
注意:我的数据库中有一个 slug 字段。
根据 user3158900 的建议,我已经尝试过:
public function setTitleAttribute($title){
$this->title = $title;
$this->attributes['slug'] = str_slug($this->title , "-");
}
//
这使我的标题字段为空,但以我想要的方式保存了 slug,为什么 $this->title 为空呢? 如果我删除 $this->title = $title; title 和 slug 都是空的
【问题讨论】: