Search functionality in Laravel

Avinash Nethala
justlaravel
Published in
3 min readAug 5, 2018

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.

Search functionality in laravel — jusLaravel.com

Search form :

First, let’s create a form for a 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 the 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.

Look at the screenshots below,

Search functionality in laravel — jusLaravel.com
Search functionality in laravel — jusLaravel.com
Search functionality in laravel — jusLaravel.com

--

--