Laravel Use Slugs Instead of ID

Created At: 2022-04-09 04:10:49 Updated At: 2022-04-09 21:05:05

Slugs are important when it comes to seo friendly url. We will see how to use slugs for url instead of ID.

1. Database column

First you need to create a column name "slug" in your database column related to post or articles.

2. Create slug

When you post an article to your database, you should send strings for your slug. You can have any custom slug column or use your article or post's title as slug.

3. Model method

In your model class(each post or article controller should have a model), insert the below function

public function getRouteKeyName(){
   //slug is a string and this string is the column in your database you created.
   return "slug";
}

slug is a string and this string is the column in your database you created

4. Setup a route

Route::get("/{slug}", "ArticleController@detail");

Replace the controller as your own controller name.

5. Controller method

In your controller method, you need to route model binding. Route model binding is injecting model object in the parameter of the controller method.

   public function detail(Article $slug)
    {
 
      
        return view('detail',[ 'article'=>$slug]);
    }

In this case I am using Article as model object. We created an object name $slug from Article model. Using this $slug object we can access the slug from the database.

6. Using slug for href

Now we need to use the $slug object in blade. It will reflect as article in the blade

<a href="/{{$article->slug}}">
  .........
  ..........

</a>

Comment

Add Reviews