Cara Custom Halaman 404 Page Not Found di Laravel

Cara Custom Halaman 404 Page Not Found di Laravel

sobatcoding.com - Tutorial membuat custom halaman 404 page not found di Laravel

Bagaimana jika kita ingin merubah halaman 404 not found bawaan Laravel yang masih standar seperti ini

Not Found Page

kita ubah sesuai dengan tampilan yang kita inginkan?

Ternyata cara membuat custom halaman di Laravel sangatlah mudah, berikut langkah-langkahnya

Buka file Handler.php yang ada di dalam folder app/Exceptions. Kemudian tambahkan handler seperti berikut:

<?php

namespace App\Exceptions;

use Illuminate\Database\Eloquent\ModelNotFoundException; //tambahkan line berikut


class Handler extends ExceptionHandler
{

   //tambahkan fungsi berikut

   /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Throwable $exception)
    {
        
        if ($exception instanceof ModelNotFoundException) {
            
            return response()->view('errors.not_found');
        }

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

Fungsi diatas berfungsi untuk overwrite fungsi abort 404 bawaan laravel, dan kita ubah dengan tampilan error menggunakan blade view bernama not_found.blade.php

Selanjutnya buatlah sebuah file blade view baru bernama not_found.blade.php dan simpan di folder app/resources/views/errors

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Error Page | sobatcoding.com</title>
    <meta name="description" content="Login member area sobatcoding.com">
    <link rel="shortcut icon" href="https://sobatcoding.com/dist/img/icon-v2.png" type="image/png">

    <link rel="stylesheet" href="https://sobatcoding.com/dist/css/app_new.css?id=dafc9de55fcf08399153fbb0056bac19">

</head>
<body>
    <div class="d-flex">
        <div class="w-100">
            <div class="page-content d-flex align-items-center justify-content-center">
                <div class="col-md-8 col-xl-6 mx-auto d-flex flex-column align-items-center">
                    <img src="https://sobatcoding.com/dist/svg/404.svg" class="img-fluid mb-2" alt="404"/>
                    <h2>Halaman tidak ditemukan :(</h2>
                    <p>Oops! 😖 Halaman yang kamu request tidak ditemukan di dalam server.</p>
                    <a href="https://sobatcoding.com" class="btn btn-primary">Kembali ke Beranda</a>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Testing

Kita coba untuk test hasil custom fungsi tersebut. Caranya kita coba buat sebuah query

<?php

$user = User::findOrFail($id) ;

 

Jika data tersebut tidak ditemukan maka , output view yang dihasilkan seperti berikut

Laravel Not Found

Demikian tutorial kali ini. Semga bermanfaat