Monsta Jams
Monsta Jams

Reputation: 23

My Slug Route Return 404 in my Laravel Code

I have stored my slug in my database but i get 404 Not found when i load the url

NewsController.php

public function show(News $news, $slug)
{   
   return view('news.single', compact('news'));
}

News.php

protected static function boot() {
    parent::boot();

    static::creating(function ($news) {
        $news->slug = Str::slug($news->subject);
    });
}

Route

Route::get('/news/{slug}', 'NewsController@show')->name('news.show');

I am getting 404 not found if load e.g localhost:8000/news/sample-post

Upvotes: 0

Views: 1340

Answers (1)

Thomas
Thomas

Reputation: 8849

The problem is that you are type-hinting News $news in your controller method and Laravel is unable to find the correct object because 1. there's no {news} route parameter and 2. it's looking in the ID column by default.

There are two options to fix it:

1. Manually load the news

public function show($slug)
{   
   $news = News::where('slug', $slug)->firstOrFail();
   return view('news.single', compact('news'));
}

2. Tell Laravel to use the slug column instead of id:

Add this method to your News model:

/**
 * Get the route key for the model.
 *
 * @return string
 */
public function getRouteKeyName()
{
    return 'slug';
}

Change the route parameter name:

Route::get('/news/{news}', 'NewsController@show')->name('news.show');

And finally, remove the $slug controller method parameter:

public function show(News $news)
{   
   return view('news.single', compact('news'));
}

Upvotes: 1

Related Questions