Search code examples
laravelsearchhttp-status-code-404

basic search in laravel didn't work without error hints


i am trying to search data from table 'pegawai' by name, but when i try to search it, it show '404 not found', i try here and there but because there's no error hints now i am stuck.

this is the route

Route::get('/pegawai/cari', 'PegawaiController@cari');

PegawaiController

public function cari(Request $request)
    {
        // menangkap data pencarian
        $cari = $request->cari;

        // mengambil data dari table pegawai sesuai pencarian data
        $pegawai = DB::table('pegawai')
        ->where('pegawai_nama', 'like', "%".$cari."%")
        ->paginate(10);

        // mengirim data pegawai ke view index
        return view('index',['pegawai' => $pegawai]);

    }

view index

<form action="/pegawai/cari" method="GET">
        <input type="text" name="cari" placeholder="Cari Pegawai .." value="{{ old('cari') }}">
        <input type="submit" value="CARI">
    </form>

the image above is what i try with the code, but no results. what mistake did i make here? and how can i get the search result i want without changing the method/code too much?


Solution

  • I suggest you name your routes

    So, your route will be like this

    Route::get('pegawai/cari', 'PegawaiController@cari')->name('pegawai.search');
    

    Then in your blade, you will call the route by its name.

    <form action="{{route('pegawai.search')}}" method="GET">
            <input type="text" name="cari" placeholder="Cari Pegawai .." value="{{ old('cari') }}">
            <input type="submit" value="CARI">
        </form>
    

    Possible Reason for your problem

    if you use a route in your blade (typical monolithic web app / website) without using route names, its possible to get the url / uri wrong because if you are already in a path (eg. /user/profile), and you write /pegawai/cari it possible the url path will be domain.com/user/profile/pegawai/cari instead of domain.com/pegawai/cari So using the route names will make the app write the exact path you intended.

    In Laravel its called Named route

    Link below

    https://laravel.com/docs/9.x/routing#named-routes