P
P
Petya Fox2019-05-27 14:36:34
Laravel
Petya Fox, 2019-05-27 14:36:34

How to setup slug in Laravel?

Guys, the problem is that I created the pages table in Laravel, through which I now generate routes for the pages. But, for example, if I enter this kind of URL: domain/hfu8vhrucnd - instead of a 404 error, it crashes - " Trying to get property of non-object ".
How can I make the application give a 404 error instead of "Whoops! There was an error."
Route:

Route::get('/{slug?}', '[email protected]')->name('page');

Controller:
public function page($slug) {
 return view('template.pages', [
  'pages' => Page::where('slug', $slug)->first()
 ]);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Talalaev, 2019-05-27
@fullstackru

The simplest way is:

public function page($slug) {
$page = Page::where('slug', $slug)->firstOrFail();

return view('template.pages', [
  'pages' => $page
 ]);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question