Home » Laravel » Laravel – Create SEO friendly URLs with slugs easily!

Laravel – Create SEO friendly URLs with slugs easily!

Recently, I discovered Laravel, a framework that should be considered of public utility because of its flexibility, ease of learning, ease of use and an undeniable asset, its very large community.

I took advantage of the redesign of my library management tool to get started and I can tell you that I was not disappointed. So I decided to share with you a few points, which I find interesting and useful during the development of my project.

So I needed to create SEO Friendly URLs thanks to slugs, like the ones you can find by default on WordPress. By default, the URLs of your Laravels templates are only made of your template IDs (except the endpoints used by default: edit, create, etc.).

For the show function of my Book controller, I wanted to have a URL consisting of the ID of my book and a slug automatically generated from the title. Here is what you want to get :

https://www.mondomaine.com/book/1/book-title

For this article, I will start from my example, that is to say a Book class composed of an id and a title attribute. To make it simple, the slug will be a “slugified” version of the title of my book.

Creating the slug

As a first step, we will create the slug attribute for our book as follows:

<?php

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    public function getSlugAttribute(): string
    {
        return str_slug($this->title);
    }
}

Routing management

In your route file, web.php, the URL format we want looks like this:

Route::get('/book/{id}/{slug?}', 'BookController@show')->name('book.show');

To simplify our lives, I make the slug parameter not mandatory in my route. At first, I won’t use it in my controller.

Controller Management

In the BookController, nothing really changes. We only take the ID into account, as before the slug was set up.

<?php

use App\Models\Book;

class BookController
{
    public function show($id)
    {
        return view('book.show')
            ->withBook(Book::findOrFail($id));
    }
}

Using your SEO Friendly URL

Now, in your Blade templates, you can generate a SEO Friendly URL to access the view of your Book object.

{{ route('book.show',[$book->id, $book->slug])}}

To go beyond

If you don’t want to leave it at that, I offer you some additional code snippets 😉

Generate a URL attribute for your Object

It can be useful to have, directly in your object, a url attribute containing the complete and already generated URL leading to the object view.

<?php

class Book extends Model
{
    // ...

    public function getUrlAttribute(): string
    {
        return action('BookController@show', [$this->id, $this->slug]);
    }
	
	// ...
}

You can now use the $book->url attribute in your Blade views or directly in your project’s PHP.

Avoid duplicate content

With the creation of slugs for your object, you may have several URLs for the same entity. Either because you still have links without slugs running on your site, or a poorly formed slug. To solve this problem, I propose two solutions, either automatically redirecting to the right page if the slug is not the right one, or by setting up a canonical tag.

Automatic redirection

To automatically redirect a bad URL, I suggest you check if the slug given in the URL corresponds to the slug generated by our attribute added above. If the slug does not match, we automatically redirect to the right URL.

To automatically redirect a bad URL, I suggest you check if the slug given in the URL corresponds to the slug generated by our attribute added above. If the slug does not match, we automatically redirect to the right URL.

Generating a canonical meta

Some don’t like redirections and would prefer a gentler solution, via the installation of a canonical beacon.

As a reminder, this is what a canonical meta is

A Canonical Tag is used to indicate to search engines such as Google or Bing the fact that a web page is duplicated and includes the content of another document. This tag then contains the address of the original page, called canonical.

Let’s go to the code. First, you need to add a canonical tag (only if it exists) in your layout file, by default : app.blade.php

...
  <head>
    @if(isset($canonical))
    <link rel="canonical" href="{{ $canonical }}" />
    @endif
  </head>
...

In your controller, it is now necessary to add the passage of the canonical beacon to the view, like this

<?php

use App\Models\Book;

class BookController
{
    // ...
    public function show($id, $slug = '')
    {
        $book = Book::findOrFail($id);

        return view('book.show')
            ->withBook($book)
            ->withCanonical($book->url);
    }
    // ...

That’s it, you now have a page accessible from a clearly more readable URL and more SEO Friendly for your Laravel models. Don’t hesitate if you have any suggestions or corrections, I’m interested 😉

Featured image : lmonk72 / Pixabay

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.