Tasmin's avatar

Showing Search Result Without Reloading Page

I am very new in Laravel. I my project I can search for items and show the search result properly. But I want to show the search result without reloading the page. Can somebody guide me?

0 likes
3 replies
gabrielbuzzi's avatar

You can easly do this creating an ajax request and loading in the page on success

First create a route

Route::get('search', 'SearchController@find');

Then create the method in the Controller

// app/Http/Controllers/SearchController.php

public function find(Request $request) 
{
    $query = User::select('*');

    if ($request->input('q')) {
        $query->where('name', 'like', "%{$request->input('name')}%");
    }
    
    $results = $query->orderBy('created_at', 'desc')->get();

    return view('search.find', compact('results'));
}

and finally in you javascript you can do something like this, i suppose that you're using jQuery.

$(document).on('submit', 'form#search', function (e) {
    
    var q = $(this).find('input[name=q']).val();

    $.ajax({
        type: 'GET',
        dataType: 'html',
        url: '/search',
        data: {
            q: q
        },
        success: function (data) {
            // Do some nice animation to show results
            $('#searchdata').html(data);
        }
    });

    e.preventDefault();
});

This is a simple way to do this.

1 like
Defcicer's avatar

To anyone seeing this after so long, Tasmin is right, this doesnt work because of the return function

 return view('search.find', compact('results'));

This returns the view, which of course, reloads it the correct way to do it would be to return only the data you need, either with compact as he did it or maybe as a json, since ive seen a lot of people use a json, both examples below

return compact('productos'); // return an array return response()->json($productos) // return json response ​

Please or to participate in this conversation.