Search code examples
phplaravelslug

Create slug with id in Laravel


I would like to create a slug with the element ID, i have try with:

$article->slug = $article->id.'-'.Str::slug($article->name, '-');

But instead of returning me:

247-Hello-World

It saves me:

-Hello-World

It's just a post of a new article, Example, if the previous article was ID 246, This article becomes 247-Slug-a-b-c. How do I pick up the ID that this article will have?


Solution

  • Try creating the slug AFTER creating the article.

    $article->save();
    $articleID = $article->id;
    $article->slug = $articleID.'-'.Str::slug($article->name, '-');
    $article->save();
    

    Reference for getting the id of the model »