Laravel 5 custom 404 controller
I am making a laravel application that has a CMS with pages stored in a database. A page record in a database has an id, title, content and url.
I want that if someone visits the url, it loads the page to display the content of that page. So I think I need to override the 404 handler to tell the user to navigate to mysite.com/about before he checks the database to see if there is a record stored as a url. If there is, then it will load the page to show the content, or if not, then it will be 404. I'm 90% from there with the following solution:
I changed the render method in app \ Exceptions \ handler.php as follows:
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
$page = Page::where('url', '=', Request::segment(1))->first();
if(!is_null($page)) {
return response(view('page', [ 'page' => $page ]));
}
}
return parent::render($request, $e);
}
This works, however there is a problem, all my menus are also stored in the database and I have a created FrontendController that gets all the menus from the database loaded into views. All of my controllers extend FrontendController so this is done on every page load and I don't have to repeat the code. So is there a way I can route all 404s through the controller instead so that it can extend my FrontendController? Or do I just have to repeat all the logic that the front end controller does in the exception handler file?
source to share