jeudi 26 mai 2016

Don't change slug on update (In Laravel Model)

I have a model called Oglas with which I create rows in table. It creates a unique slug for that row, but whenever I update that row it generates new slug. So when someone shares a post, then edit, that shared post doesn't exists anymore because slug is changed.

Here is code 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;
        }



}

To summarize: When creates new post fire that slug creation, when updating (editing) don't fire, don't change slug.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire