Search functionality in Laravel

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

Search form :

First lets create a form for search field,

{{ csrf_field() }}

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 !’); });

Route::any(‘/search’,function(){     $user = User::where(‘name’,’LIKE’,’%’.$q.’%’)->orWhere(’email’,’LIKE’,’%’.$q.’%’)->get();         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 controller.

Search results :

Welcome view for showing search results will look like,

@if(isset($details))

The Search results for your query {{ $query }} are :

Sample User details

@foreach($details as $user) @endforeach

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

@endif

The Search results for your query {{ $query }} are :

Sample User details

@foreach($details as $user)

{{$user->email}}

The routes file looks like,

You might also like

More Similar Posts