Search code examples
phplaravelroutesblogs

Laravel Blog - canonical route does not work


I built a small blog controller to add a blog to my website like http://example.com/blog/post

It works fine with the post id like: http://example.com/blog/1 But it doesn't work with http://example.com/blog/postTitle

Here is my code:

Routes:

Route::get('/blog/{blogPost}', ['as' => 'blogPost', 'uses' => 'BlogPostController@show']);

BlogPostControler.php :

public function show(BlogPost $blogPost)
    {
        return view('blog.show', [
                'post' => $blogPost,
        ]);
    }

views/blog/index.blade.php :

From here I link to the blog posts. When i change the <a href="blog/{{ $post->title_slug }}">{{ __('blog.Read more') }}</a> back to <a href="blog/{{ $post->id }}">{{ __('blog.Read more') }}</a> it works fine

<div class="box">
    @forelse($posts as $post)
            <ul>
                <li>
                    <h3>{{ ucfirst($post->title) }}</h3>
                    <p>{!! mb_substr(strip_tags($post->body), 0, 255) !!} ... <a href="blog/{{ $post->title_slug }}">{{ __('blog.Read more') }}</a> </p>

                </li>
            </ul>
        @empty
            <p class="text-warning">No blog Posts available</p>

    @endforelse

    </div>

As I said, it works fine with the id. What did I wrong? I can't figure it out.

Thank you all

I think I have to check whether the title_slug fits to the post id. But I don't know where. I use Laravel v5.8.3


Solution

  • You may change the route key/database column that is used when binding a model.

    As per the documentation (see: Customizing the key name):

    If you would like model binding to always use a database column other than id when retrieving a given model class, you may override the getRouteKeyName method on the Eloquent model.

    public function getRouteKeyName(): string
    {
        return 'title_slug';
    }
    

    After you add that function to your BlogPost model, using the slug in the URL should work.