tuscan88
tuscan88

Reputation: 5829

Laravel 5 custom 404 controller

I am making laravel app that has a CMS with pages stored in the database. A page record in the database has an id, title, content and url slug.

I want it so that if someone visits the url slug then it will load a page to display the content of that page on. So I think I need to override the 404 handler so that say the user goes to mysite.com/about before it 404's it checks the database to see if there is a record with about stored as the url slug. If there is then it will load the page to show the content, or if not then it will 404. I'm 90% of the way there with the following solution:

I have modified the render method in App\Exceptions\handler.php to be the following:

/**
 * 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 of my menus are stored in the database as well and I have a made FrontendController that gets all of the menus from the database to be loaded into the views. All of my controllers extend FrontendController so that this is done on every page load and I don't have to repeat any code. So is there a way that I can route all 404s through a controller instead so that it can extend my FrontendController? Or am I just going to have to repeat all of the logic that the front end controller does in the exceptions handler file?

Upvotes: 4

Views: 2648

Answers (1)

tuscan88
tuscan88

Reputation: 5829

Solved it! Thanks to Styphon for giving me the idea, I just defined the following route as my very last route:

Route::get('/{url}', 'FrontendController@page');

Upvotes: 4

Related Questions