Search functionality in Laravel

30. April 2016 Intermediate, Laravel 36
Search functionality in Laravel

Here we ‘ll see how to implement search functionality in Laravel. we ‘ll search the data from the database and show the search results in a table.

Working Demo      Project on Github

You can also watch this video on YouTube here

Search form :

First, let’s create a form for search field,

<form action="/search" method="POST" role="search">
    {{ csrf_field() }}
    <div class="input-group">
        <input type="text" class="form-control" name="q"
            placeholder="Search users"> <span class="input-group-btn">
            <button type="submit" class="btn btn-default">
                <span class="glyphicon glyphicon-search"></span>
            </button>
        </span>
    </div>
</form>

Search action :

When the search button is clicked, it goes to the route search where the logic for fetching data from database is present,

Route::any('/search',function(){
    $q = Input::get ( 'q' );
    $user = User::where('name','LIKE','%'.$q.'%')->orWhere('email','LIKE','%'.$q.'%')->get();
    if(count($user) > 0)
        return view('welcome')->withDetails($user)->withQuery ( $q );
    else return view ('welcome')->withMessage('No Details found. Try to search again !');
});

this logic searches the table User for name and email with the input we provide, here we use LIKE operator for searching data,
after fetching the data the data is sent to welcome view, along with the message when no search results are found.

Here all the logic is written in routes file itself, if we want to create a controller we can do it, here only just one simple logic, so we didn’t use a controller.

Search results :

Welcome view for showing search results will look like,

<div class="container">
    @if(isset($details))
        <p> The Search results for your query <b> {{ $query }} </b> are :</p>
    <h2>Sample User details</h2>
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            @foreach($details as $user)
            <tr>
                <td>{{$user->name}}</td>
                <td>{{$user->email}}</td>
            </tr>
            @endforeach
        </tbody>
    </table>
    @endif
</div>

The routes file looks like,

<?php
use App\User;
use Illuminate\Support\Facades\Input;

Route::get ( '/', function () {
    return view ( 'welcome' );
} );
Route::any ( '/search', function () {
    $q = Input::get ( 'q' );
    $user = User::where ( 'name', 'LIKE', '%' . $q . '%' )->orWhere ( 'email', 'LIKE', '%' . $q . '%' )->get ();
    if (count ( $user ) > 0)
        return view ( 'welcome' )->withDetails ( $user )->withQuery ( $q );
    else
        return view ( 'welcome' )->withMessage ( 'No Details found. Try to search again !' );
} );

for different types of routing check previous post on routing.

Now when someone queries the database, we can see the appropriate results.

Working Demo      Project on Github

Look at the screenshots below,

Search functionality in laravel - jusLaravel.com
Search functionality in laravel – jusLaravel.com
Search functionality in laravel - jusLaravel.com
Search functionality in laravel – jusLaravel.com
Search functionality in laravel - jusLaravel.com
Search functionality in laravel – jusLaravel.com
Search functionality in laravel - jusLaravel.com
Search functionality in laravel – jusLaravel.com
Search functionality in laravel - jusLaravel.com
Search functionality in Laravel – justlaravel.com

Working Demo      Project on Github

That’s it, folks. We have successfully implemented simple search functionality for fetching data from database in Laravel.

Feel free to browse previous posts on custom authentication with validation, routing, and pagination.



36 thoughts on “Search functionality in Laravel”

  • 1
    longkyanh on April 30, 2016 Reply

    return view(‘welcome’)->withDetails($user)->->withQuery ( $q );
    ? should it be only one `->` pointer

    • 2
      avinash on April 30, 2016 Reply

      Thanks longkyanh for the check, corrected it now. 🙂

  • 3
    Cris on July 13, 2016 Reply

    I recommend you use the “when” of laravel 5.2 to optimize and refactor this code. regards

    • 4
      avinash on July 13, 2016 Reply

      Thanks Cris for the update,

      I think, i made this search functionality post with laravel 5.1~

  • 5
    Michelle Prather on December 14, 2016 Reply

    Code from last question :

    //routes.php
    Route::any(‘/search’,function(){
    $q = Input::get ( ‘q’ );
    $trucking_delivery = TruckingDelivery::where(‘ref_no’,’LIKE’,’%’.$q.’%’)->orWhere(‘mawb’,’LIKE’,’%’.$q.’%’)->orWhere(‘hawb’,’LIKE’,’%’.$q.’%’)->get();
    if(count($trucking_delivery) > 0)
    return view(‘search-results’)->withDetails($trucking_delivery)->withQuery ( $q );
    else return view(‘freight-availability’)->withMessage(‘No Details found. Please try your search again !’);
    });

    • 6
      avinash on December 15, 2016 Reply

      You try Session Flash Session::flash ( 'message', 'No Details found. Please try your search again !' );

      and then in you view,

      @if ((Session::has('message')))

      {{
      Session::get('message') }}

  • 7
    leicha on January 13, 2017 Reply

    does this work on laravel 5.3.28?

    i dont get any results at all

    but when i delete the lines:

    @if(isset($details))
    The Search results for your query {{ $query }} are :

    i get:

    Undefined variable: details

    • 8
      avinash on January 13, 2017 Reply

      It will work on 5.3 too

      That `$details` variable contains the search results. So a check is made whether results are available are not.

      Make sure the variable `$user` is getting any results in getting any response.(in routes file here)

  • 9
    Ho Dang KHoa on March 4, 2017 Reply

    thank

  • 10
    brunopy on April 24, 2017 Reply

    Where are the methods withDetails and withQuery documented? I’ve been looking through the whole documentation with no success.

    • 11
      avinash on April 24, 2017 Reply

      `withDetails` and `withQuery` are not laravel methods they are called magic functions. Which means when we use `withSomename` in Controller here, we can access them in view as `$somename`. Take a look at the case of the letters, withCapital in controller —- $capital in view.

      Hope it helps, revert back if not clear.

  • 12
    dbetmDavid on June 11, 2017 Reply

    q, Input does not exists

    • 13
      avinash on June 11, 2017 Reply

      Make sure you have used `use Illuminate\Support\Facades\Input;` at the top of the controller.

  • 14
    nazarethgroup on June 13, 2017 Reply

    When I click on Search , Its redirecting me to localhost/search.
    Please Help, I downloaded the code through github, and I followed the step, but when I click on Search its redirecting me to localhost/search instead of localhost/searchfunctionality/search.
    I’ve checked the route and it look good
    PLEASE HELP
    orWhere ( ’email’, ‘LIKE’, ‘%’ . $q . ‘%’ )->get ();
    if (count ( $user ) > 0)
    return view ( ‘welcome’ )->withDetails ( $user )->withQuery ( $q );
    else
    return view ( ‘welcome’ )->withMessage ( ‘No Details found. Try to search again !’ );
    } );

  • 15
    outa on August 21, 2017 Reply

    When I try this I get error Class ‘App\Posts’ not found

  • 16
    Sanchit Mahajan on October 15, 2017 Reply

    How to write above code in Laravel 5.3.. I am getting error… thank You.

    • 17
      avinash on October 15, 2017 Reply

      What is the error you are getting?

  • 18
    Sanchit Mahajan on October 16, 2017 Reply

    Error in Route function.. How to make this example using controller? thanks…

    • 19
      avinash on October 18, 2017 Reply

      Replace this line `Route::any(‘/search’,function(){…….});` with `Route::any(‘/search’,YourController@functionName);` and place the code in the controller

  • 20
    hanin on April 27, 2018 Reply

    any advice for using search for each column I am begginer in laravel and I need your help

  • 21
    Sam on May 21, 2018 Reply

    thanks for the amazing explanation, the foreach duplicate the value.
    when i run this code in my code, not for user for a search result
    @foreach($details as $user)

    {{$user->name}}
    {{$user->email}}

    @endforeach

    it appears as three duplicated rows.

  • 22
    Alex Muchiri on June 18, 2018 Reply

    Hello, I’m clicking the search button without inserting any query and it displays all the data in my database. I want it to display “No Details No found. Try to search again!” when one doesn’t type a query.

    Please help

    • 23
      avinash on June 18, 2018 Reply

      You can add an if condition like

      if($q != “”){
      $user = User::where ( ‘name’, ‘LIKE’, ‘%’ . $q . ‘%’ )->orWhere ( ’email’, ‘LIKE’, ‘%’ . $q . ‘%’ )->get ();
      if (count ( $user ) > 0)
      return view ( ‘search-functionality-in-laravel/welcome’ )->withDetails ( $user )->withQuery ( $q );
      }

      Also update the code on github, please check
      https://github.com/avinashn/searchexamplelaravel

  • 24
    Alex on June 18, 2018 Reply

    Hello, I’m clicking the search button without inserting any query and it displays all the data in my database. I want it to display “No Details No found. Try to search again!” when one doesn’t type a query/ Please help

  • 25
    Alex Muchiri on June 26, 2018 Reply

    Thank you, it worked.

  • 26
    Josef on September 26, 2018 Reply

    The term Input in $q =Input::get is giving an exception. That Class Input is not found

    • 27
      avinash on September 28, 2018 Reply

      You need to import Input as, use Illuminate\Support\Facades\Input;

  • 28
    aschalew on February 1, 2019 Reply

    Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
    Call to undefined method Illuminate\Database\MySqlConnection::get()
    it say when i was run please help me

  • 29
    John McLem Adan on October 14, 2019 Reply

    Hi Avinash. Thanks for posting this tutorial. However I get an error saying that $query is undefined. Any kind of help will be appreciated. Thanks

    • 30
      avinash on October 14, 2019 Reply

      Make sure you are using the following line in the function.
      return view ( ‘welcome’ )->withDetails ( $user )->withQuery ( $q );

      if you have “withQuery($q)”, you can access $query in your view.

  • 31
    John McLem Adan on October 15, 2019 Reply

    Hi Avinash. Thanks for the reply. However I got another error saying “Symfony\Component\Debug\Exception\FatalThrowableError
    Class ‘Illuminate\Support\Facades\Input’ not found” even if I already declared “use Illuminate\Support\Facades\Input;”

    • 32
      avinash on October 15, 2019 Reply

      You need to import the `Input` facade like so `use Illuminate\Support\Facades\Input;`

  • 33
    John McLem Adan on October 22, 2019 Reply

    HI Avinash. Thanks, I finally got it working but all of a sudden it threw an error saying “The GET method is not supported for this route. Supported methods: POST.” after testing the working functionality for few times. Any help will be appreciated. Thank you.

  • 35
    dona on May 11, 2020 Reply

    hi im on laravel 7 and i get Class ‘Illuminate\Support\Facades\Input’ not found pls help

Leave a Reply