Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading