skip to Main Content

I want to SEO-up my laravel URLs, so I want to change www.example.com/posts/32 to www.example.com/posts/how-to-name-routes

I see that I can manually name routes by chaining the name() method on the route, but I want the name to be automatically filled from the title of the post. The titles, however, contain spaces So my Post object would have the title 'How to name routes' but the URL would be www.example.com/posts/how-to-name-routes

Do I need to implement my own string manipulation system or is this something Laravel handles already?

2

Answers


  1. You could add a unique slug column for your Posts table and then use that as the parameter in your routes e.g. '/posts/{slug}'.

    You can add a mutator for this inside your Post model:

    public function setTitleAttribute($title)
    {
        $this->attributes['slug'] = str_slug($title);
        $this->attributes['title'] = $title;
    }
    
    Login or Signup to reply.
  2. My recommendation would be to implement a slug field on your Post model and use that as the key for Route Model Binding.

    To slugify the post title, use Laravel’s Muttators to convert the post title to a URL friendly slug.

    To ensure that slugs are unique, you can append the timestamp to the slug, preserving SEO while removing conflicts on the column.

    
        /**
    
         * Set the post's slug.
         *
         * @return void
         */
        public function setSlugAttribute()
        {
            $this->attributes['slug'] = Str::slug($this->attributes['title']) . dechex(time());
        }
    
    

    After creating a slug field, you can bind it to the route by overriding the getRouteKeyName method in your Post model.

    
        public function getRouteKeyName()
        {
            return 'slug';
        }
    
    

    Your routes will become something like

    
        Route::get('posts/{post}', 'PostsController@getPost');
    
    

    References:
    Route Model Binding:
    https://laravel.com/docs/5.8/routing#route-model-binding
    Slug Helper:
    https://laravel.com/docs/5.8/helpers#method-str-slug
    Eloquent Mutators:
    https://laravel.com/docs/5.8/eloquent-mutators

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search