Laravel how to make a search

Laravel: Learn how to create a powerful search feature with an example.

Creating a Search Feature in Laravel

In this tutorial, we will look at how to create a basic search feature in Laravel. We will cover the following topics:
  • Creating the Search Controller
  • Creating the Search View
  • Creating the Search Route
  • Making the Search Form Functional

Creating the Search Controller

The first step in creating a search feature in Laravel is to create a controller. This controller will be responsible for handling the search functionality. To create the controller, open the command line and navigate to the root of your project. Then, run the following command:
php artisan make:controller SearchController
This will create a controller file in the app/Http/Controllers directory. Open the file and add the following code:
<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class SearchController extends Controller
{
    /**
    * Handle the incoming request.
    *
    * @param  IlluminateHttpRequest  $request
    * @return IlluminateHttpResponse
    */
    public function __invoke(Request $request)
    {
        //
    }
}
This code will create an empty controller that will handle the incoming request.

Creating the Search View

The next step is to create a view where the search form will be displayed. To do this, create a new file in the resources/views directory and name it search.blade.php. Then, add the following code:
<form action="{{ route('search') }}" method="GET">
  <input type="text" name="query">
  <input type="submit" value="Search">
</form>
This code will create a basic search form with an input field and a submit button. The form will submit a GET request to the search route.

Creating the Search Route

The next step is to create a route for the search form. To do this, open the routes/web.php file and add the following code:
Route::get('/search', 'SearchController')->name('search');
This will create a route for the search form. When the form is submitted, the request will be handled by the SearchController.

Making the Search Form Functional

The final step is to make the search form functional. To do this, open the SearchController and add the following code:
public function __invoke(Request $request)
{
    $query = $request->input('query');
    $results = Model::where('name', 'LIKE', "%$query%")
        ->orWhere('description', 'LIKE', "%$query%")
        ->get();
        
    return view('search', compact('results'));
}
This code will retrieve the search query from the request and use it to search the model for matches. The results will be passed to the search view. And that's it! You now have a functioning search feature in Laravel. You can now add additional functionality to make the search more powerful, such as adding advanced search options or including additional fields in the search query.

Answers (0)