Laravel Route Model Binding With Slug

Laravel Route Model Binding With Slug
In Laravel, route model binding provides a streamlined way to automatically inject model instances into routes, saving time and reducing the need for manual queries. Typically, route model binding uses the primary key (usually the id field), but in many cases, you may want to use a more user-friendly field like a slug. This guide will walk you through how to implement Laravel route model binding with slug efficiently.

Table of Contents

What is Route Model Binding in Laravel?

Route Model Binding in Laravel is a feature that automatically injects an instance of a model into your route based on a route parameter. This allows you to avoid writing manual database queries in your controllers to retrieve model data. Laravel provides two types of route model binding: implicit and explicit.

Implicit Route Model Binding

Implicit binding is the simplest form and is often used with primary keys like id. Laravel automatically resolves the route parameter to a corresponding model.

Example:

If you have a route like this:
				
					Route::get('/users/{user}', [UserController::class, 'show']);

				
			
And a controller method:
				
					class UserController extends Controller
{
    public function show(User $user)
    {
        return view('users.show', compact('user'));
    }
}

				
			

When a user visits /users/1, Laravel will automatically fetch the user with id 1 from the database and pass the User model instance to the show method.

Explicit Route Model Binding

Explicit binding allows you to bind a specific route parameter to a model using a custom query. This is useful if you want to bind a model based on a field other than the primary key, such as a slug.

Example:

In the RouteServiceProvider:
				
					use App\Models\Post;

public function boot()
{
    Route::model('post', Post::class);
}

				
			

Now, you can define a route with the {post} parameter, and Laravel will automatically fetch the Post model based on the default key or a custom key like a slug if defined in the model.

Why Use Slug for Route Binding?

A slug is a URL-friendly version of a string, typically used for SEO-friendly URLs. For example, instead of /posts/12, you can have /posts/laravel-tutorial where laravel-tutorial is a slug. It’s more readable and better for SEO.

Setting Up Route Model Binding with Slug

To set up route model binding with a slug, follow these steps:

Step 1: Add a Slug Field to Your Model

First, ensure your model has a slug field. If it doesn’t, you’ll need to add it. Create a migration to add the slug column to your database table.
				
					php artisan make:migration add_slug_to_posts_table --table=posts

				
			
In the generated migration file, add the following code:
				
					public function up()
{
    Schema::table('posts', function (Blueprint $table) {
        $table->string('slug')->unique();
    });
}

				
			
Run the migration:
				
					php artisan migrate

				
			

Step 2: Update Your Model

Update your model (e.g., Post) to include the slug. Make sure your model has a method to fetch records by slug instead of id.

				
					class Post extends Model
{
    protected $fillable = ['title', 'content', 'slug'];

    // Find route model binding by slug instead of id
    public function getRouteKeyName()
    {
        return 'slug';
    }
}

				
			

The getRouteKeyName method tells Laravel to use the slug field for route model binding.

Step 3: Define the Route

Next, define a route that includes the slug as a parameter.
				
					Route::get('/posts/{post}', [PostController::class, 'show']);

				
			
Here, Laravel will automatically resolve the post parameter to a Post model instance using the slug.

Step 4: Implement the Controller

In your controller, you can directly use the Post model instance passed to the show method:

				
					class PostController extends Controller
{
    public function show(Post $post)
    {
        return view('posts.show', compact('post'));
    }
}

				
			

With this setup, when you visit /posts/laravel-tutorial, Laravel will automatically fetch the Post model where the slug is laravel-tutorial.

Step 5: Generate Slugs Automatically

You can use Laravel’s string helper functions to generate slugs automatically. For instance, when creating or updating a post, you can generate the slug based on the title:

				
					use Illuminate\Support\Str;

class Post extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::saving(function ($post) {
            $post->slug = Str::slug($post->title);
        });
    }
}

				
			
This ensures the slug is always generated based on the post’s title before saving it to the database.

Benefits of Using Slug in Route Model Binding

  • SEO-Friendly URLs: Using slugs improves the readability and SEO of your URLs.
  • Automatic Model Resolution: Laravel’s route model binding saves you from writing manual queries.
  • Unique Identification: Slugs act as a unique identifier, making URLs more meaningful to users.

Final Thoughts

Implementing Laravel route model binding with slug is a powerful and developer-friendly approach to enhancing your application’s URLs. With just a few tweaks in your model, routes, and controller, you can have more readable, SEO-optimized URLs while leveraging the power of Laravel’s automatic route model binding.

By following this guide, you can efficiently use slugs in your Laravel applications, providing both a better user experience and improved SEO.

Written By,

Picture of Md Monayem Islam

Md Monayem Islam

Hey, I'm Md Monayem Islam. I’m a Full Stack Developer with extensive expertise in Laravel (PHP), Vue.js (TypeScript), and API development. Over the years, I’ve honed my skills in building dynamic and scalable web applications. Previously, I worked on a variety of projects, creating robust solutions and enhancing the user experience for clients worldwide. Now, I’m here to share my knowledge and help you develop web applications.

Want a FREE Consultation?

I am here to assist with your queries. Schedule now!
Share the Post:

Let's Connect!

Have a question? Contact me and I’ll get back to you soon.

Do you Need a developer for your project?