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,





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.
return view(‘welcome’)->withDetails($user)->->withQuery ( $q );
? should it be only one `->` pointer
Thanks longkyanh for the check, corrected it now. 🙂
I recommend you use the “when” of laravel 5.2 to optimize and refactor this code. regards
Thanks Cris for the update,
I think, i made this search functionality post with laravel 5.1~
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 !’);
});
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') }}
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
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)
thank
Where are the methods withDetails and withQuery documented? I’ve been looking through the whole documentation with no success.
`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.
q, Input does not exists
Make sure you have used `use Illuminate\Support\Facades\Input;` at the top of the controller.
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 !’ );
} );
When I try this I get error Class ‘App\Posts’ not found
How to write above code in Laravel 5.3.. I am getting error… thank You.
What is the error you are getting?
Error in Route function.. How to make this example using controller? thanks…
Replace this line `Route::any(‘/search’,function(){…….});` with `Route::any(‘/search’,YourController@functionName);` and place the code in the controller
any advice for using search for each column I am begginer in laravel and I need your help
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.
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
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
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
Thank you, it worked.
The term Input in $q =Input::get is giving an exception. That Class Input is not found
You need to import Input as, use Illuminate\Support\Facades\Input;
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to undefined method Illuminate\Database\MySqlConnection::get()
it say when i was run please help me
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
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.
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;”
You need to import the `Input` facade like so `use Illuminate\Support\Facades\Input;`
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.
In the route, it is specified as any(`Route::any(…)`). So it can accept both `get` and `post`. For reference please check the code base on GitHub(https://github.com/avinashn/searchexamplelaravel).
hi im on laravel 7 and i get Class ‘Illuminate\Support\Facades\Input’ not found pls help