Ad

Unique Slug From The Same Title In Octobercms

- 1 answer

I am saving form inputs to the database with slug from the post's title this way

 $post = new Post();
       $post->title = Input::get('title');
       $post->slug = str_slug(Input::get('title'));
       ...

When two users enter exactly the same title for example "It is a new day", it generates the same slug "it-is-a-new-day" and the two posts clash. How can i fix this? Have not found a straight forward way that works yet

Ad

Answer

If adding id is acceptable you could just save it and then update

$post= new Post();
$post->title = Input::get('title');
// you don't set slug here
// ...
$post->save();

$post->update(['slug' => str_slug($post->title).'-'.$post->id]);

and if line with update doesn't work (probably because of fillable), you should use:

$post->slug = str_slug($post->title).'-'.$post->id; 
$post->save();

instead of this line.

Ad
source: stackoverflow.com
Ad