Origami
Origami

Reputation: 47

404 not found when show data by slug in laravel

I'm trying to show a post using slug but always get 404 not found.

Controller

    public function show($slug)
{
    $post = Post::findorFail($slug);
    $tags = Tag::all();

    return view('page.detail', compact('post', 'tags'));
}

Route

Route::get('/post/{slug}', 'PageController@show');

View

@foreach($post as $item)
<a href="/post/{{$item->slug}}" class="btn-custom">Read More <span
 class="ion-ios-arrow-forward">
@endforeach

Thanks

Upvotes: 0

Views: 419

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29258

findOrFail() checks against primary key of your Post.php model, which is typically id, so your query is currently:

SELECT * FROM posts WHERE id = 'contents-of-slug'

Your code should work if you do the following:

$post = Post::where('slug', $slug)->firstOrFail();

See the documentation; it shows this exact example:

https://laravel.com/docs/8.x/eloquent#not-found-exceptions

Upvotes: 4

Related Questions