更新时不要更改slug(在Laravel模型中)

时间:2016-05-26 16:29:50

标签: laravel laravel-4 laravel-5 laravel-5.1 laravel-5.2

我有一个名为Oglas的模型,我在表中创建行。它为该行创建了一个独特的slug,但每当我更新该行时,它都会生成新的slug。因此,当有人分享帖子,然后进行编辑时,由于slug已更改,该共享帖子不再存在。

以下是代码Oglas

    class Oglas extends Model
    {
        protected $table = "oglasi";
        protected $guarded = ['id'];

        public function uniqueSlug($title) {
            $slug = str_slug($title);
            $exists = Oglas::where('slug', $slug)->count();

            if($exists > 0)
                $slug .= "-" . rand(11111, 99999);

            return $slug;
        }

        public function setNazivAttribute($value) // In table i have "naziv" column
        {
            $this->attributes['slug'] = $this->uniqueSlug($value); // I do not want this to fire if post is edited.
            $this->attributes['naziv'] = $value;
        }



}

总结:当创建新的帖子火力创建slug时,当更新(编辑)不激活时,不要更改slug。

2 个答案:

答案 0 :(得分:1)

看起来雄辩的模型events是解决问题的好方法。如果你想在创建帖子时创建slug,你可以使用creating事件。

Oglas.php

上定义它
protected static function boot()
{
    parent::boot();

    static::creating(function ($oglas) {
        $oglas->slug = $this->uniqueSlug($this->naziv);
    });
}

或者您可以在AppServiceProvider.php上定义它:

public function boot()
{
    ....

    Oglas::creating(function ($oglas) {
        $oglas->slug = $oglas->uniqueSlug($oglass->naziv);
    });
}

答案 1 :(得分:0)

使用laravel的create方法,这样更新不会触发。或者使用雄辩的查询来创建。这也将保护唯一行的更新。