gpt4 book ai didi

php - Laravel 在保存前生成 slug

转载 作者:可可西里 更新时间:2023-11-01 12:23:29 25 4
gpt4 key购买 nike

我正在尝试在 this wondefull website 的帮助下学习 Laravel 5 .对于我的事件模型,我想在将一个 slug 保存到我的数据库之前生成 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 is not filled 保存对象时,我尝试将其更改为 $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 都是空的

最佳答案

我认为这是行不通的,因为您没有尝试设置一个 slug 属性,这样函数就永远不会被命中。

我建议在您的 setTitleAttribute() 函数中设置 $this->attributes['slug'] = ... 以便它在您设置标题时运行.

否则,另一种解决方案是为您的模型创建一个保存事件,并将其设置在那里。

编辑:根据评论,也有必要在此函数中实际设置 title 属性...

public function setTitleAttribute($value)
{
$this->attributes['title'] = $value;
$this->attributes['slug'] = str_slug($value);
}

关于php - Laravel 在保存前生成 slug,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30582600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com