Laravel Search Functionality


Laravel Search Functionality – The Laravel Search Functionality is used to search the data and display on the view which is matched from the database value.


Laravel Search Functionality | with full Example.

Let us understand how to use search functionality in laravel.

Full example of search functionality.

Now here i am going to explain how to use search functionality step by step.

First we have to create a controller using artisan command like this.

php artisan make:controller SearchController

Controller code:-

Let’s look at a simple example.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\TestModel;
use App\view;
use Illuminate\Support\Facades\Route;
use Validator, Redirect;
use Illuminate\Support\Facades\Auth;
use Session;
use Illuminate\Support\Facades\Input;
class SearchController extends Controller
{
public function find()
{	
return view('search');			
}		
public function findSearch()
{			
$search = Input::get ( "search" );		
$test = TestModel::where ( 'name', 'LIKE', '%' . $search . '%' )->orWhere ( 'email', 'LIKE', '%' . $search . '%' )->get ();
if (count ( $test ) > 0)
return view ( 'search' )->withDetails ( $test )->withQuery ( $search );
else
return view ( 'search' )->withMessage ( 'No Details found. Try to search again !' );		
}
}

Model code:-

Let’s look at a simple example.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class TestModel extends Model
{
   protected $table = 'test';
   protected $fillable = ['name','password','email','number','date_of_birth'];
}

view code:-

Let's look at a simple example.

<!doctype html>
<html>
<head>
<style>

</style>
</head>
<body>
<form method="post" action="http://localhost/laravel/blog/public/findSearch">				
<input type="text" name= "search">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button>Search Now</button>				
</form>
<?php
if(isset($details)){
	
	?>
	 <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>
	<?php
}
?>
</body>
</html>

Route path:-

Route::get('/find', 'AccountController@find');
Route::post('/findSearch', 'AccountController@findSearch');
Laravel Search Functionality

When we search data through name or email in search box. Output will be display like this:-

Laravel Search Functionality

Advertisements

Add Comment