Webman

Personal blog by Mark Topper

Make Custom 404 page in Geekshop

2 months ago · 1 MIN READ

So now if you go and visit a product that does not exists anymore, you will get this message, which might not fit well for the visitor.

/storage/geekshop-product-not-found-original.png

However this can easily be solved.

First open up app/Http/Controllers/ProductController.php and replace:

$product = Product::where('slug', '=', $slug)->where('active', '=', 1)->first();

with

$product = Product::where('slug', '=', $slug)->where('active', '=', 1)->firstOrFail();

Then open up the app/Exceptions/Handler.php file find:

    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

Replace that with the following:

    public function render($request, Exception $exception)
    {
        if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
            return response(view('404'));
        }

        return parent::render($request, $exception);
    }

Now it will show the 404 view whenever a product is not found. Lets try make a simple 404 view.

Create a new file located at resources/views/404.blade.php with the following content:

@extends('themes.default.layouts.app')

@section('content')
    <div class="container">
        @if(isset($search))
            <h1 class="center"><i class="geekshop-search"></i> Wow! Oh no!</h1>
        @endif
        <div class="row">
            <div class="col-md-12">
                We cannot find the page.... Maybe you can?
            </div>
        </div>
    </div>
@endsection

Then your new 404 page will look like this.

/storage/geekshop-product-not-found-new.png

Thats it! You can now do your own design for the 404 page as you will. Good luck.

Update

Some of you told me that this did not work for pages that did not exists, like /some-random-page.

However for this there is a easy fix.

First open up your routes/web.php file and add the following right after the Route::get('/', 'HomeController@index'); route:

Route::get('/404', function (){
    return response(view('404'));
});

We will use this page to show the 404 error.

Now lets open the exception handler again app/Exceptions/Handler and replace:

if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
    return response(view('404'));
}

with:

if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException || $exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
    return redirect('/404');
}

Now it works for both non-existing pages and non-existing products.

Let me know if you have any issues.

···

Mark Topper

I'm a software developer from Denmark working at Novasa Interactive ApS with the responsibility of their web servers and API structure. I am also a big contributor of open source projects on Github.
comments powered by Disqus


Proudly powered by Canvas · Sign In