Laravel Live search | Real ime search in laravel
Laravel live seach | Real time search in laravel
Controller
SearchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Departments;
class SearchController extends Controller
{
public function index()
{
$dpt=Departments::orderBy('id','desc')->get();
return view('admin.department.view',compact('dpt'));
}
public function search(Request $request)
{
$output="";
$departments=Departments::where('dpt_name','Like','%'.$request->search.'%')->orWhere('dpt_code','Like','%'.$request->search.'%')->get();
$i=0;
foreach($departments as $dpt)
{
$i=$i+1;
$output.='<tr><td>'. $i.'</td><td>' .$dpt->dpt_name.'</td><td>'.$dpt->short_name.'</td><td>'.$dpt->dpt_code.'</td><td>' . '<a href="/departments/'.$dpt->id.'/edit">'.'Edit</a>'.'| <a href="/department/delete/'.$dpt->id.'">'.' Delete</a>' .'</td></tr>';
}
return response($output);
}
}
View blade file
view.blade.php
<!DOCTYPE html>
<html>
<head>
<title>View</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<a href="/departments/create">Add department</a>
<input type="text" name="search" id="search" placeholder="Enter your keyword">
<table border="1">
<tr>
<th>SL</th>
<th>Department name</th>
<th>short name</th>
<th>Department code</th>
<th>Action</th>
</tr>
<tbody class="generaldata">
@foreach($dpt as $key=>$data)
<tr>
<td>{{++$key}}</td>
<td>{{$data->dpt_name}}</td>
<td>{{$data->short_name}}</td>
<td>{{$data->dpt_code}}</td>
<td><a href="/departments/{{$data->id}}/edit"> Edit</a>| <a onclick="return confirm('are you sure delete this data')" href="/department/delete/{{$data->id}}"> Delete</a></td>
</tr>
@endforeach
</tbody>
<tbody id="Content" class="ajaxdata"></tbody>
</table>
<script type="text/javascript">
$("#search").on('keyup',function(){
$value=$(this).val();
if($value){
$(".generaldata").hide();
$(".ajaxdata").show();
}else{
$(".generaldata").show();
$(".ajaxdata").hide();
}
$.ajax({
type:'get',
url:'{{URL::to('search')}}',
data : {'search':$value},
success:function(data){
console.log(data);
$('#Content').html(data);
}
});
})
</script>
</body>
</html>
Route
Route::get('/SearchIndex','SearchController@index');
Route::get('/search','SearchController@search');
No comments