Last active
October 18, 2020 05:25
-
-
Save elbosp/f3c8e4786fcfd16398fad929a5a9ae76 to your computer and use it in GitHub Desktop.
live search with php (laravel framework)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Illuminate\Database\Eloquent\Builder; // JANGAN LUPA INCLUDE ELOQUENT BUILDER | |
return view('some_view', [ | |
// LEMPAR QUERY SEARCH SEBELUMNYA | |
'search' => request()->search, | |
// MENGGUNAKAN FUNCTION WHEN, CHECK: https://laravel.com/docs/8.x/collections#method-when | |
// MENGGUNAKAN FUNCTION WHEREHAS, CHECK: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence | |
'models' => Model::when(request()->search, function($qwr) { | |
$qwr->whereHas('child_relation', function (Builder $query) { | |
$query->where('column_name', 'LIKE', '%' . request()->search . '%') | |
->orWhere('column_name_2', 'LIKE', '%' . request()->search . '%'); | |
}) | |
->orWhereHas('child_relation.grandchild_relation', function (Builder $query) { | |
$query->where('column_name', 'LIKE', '%' . request()->search . '%') | |
->orWhere('column_name_2', 'LIKE', '%' . request()->search . '%'); | |
}) | |
})->paginate(10) | |
]); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// FORM SEARCH | |
// METHOD: GET | |
// ACTION TO ROUTE CONTROLLER SERACH | |
<form action="{{ route('search_controller') }}" method="GET"> | |
// INPUT SERACH DENGAN VALUE SERACH VARIABLE SEBELUMNYA YANG DILEMPAR MELALUI CONTROLLER | |
<input name="search" type="text" value="{{ $search }}"> | |
// BUTTON SEARCH | |
<button type="submit">Pencarian</button> | |
<form> | |
// MENULIS DATA DI DATATABLE | |
<table> | |
<thead> | |
<tr> | |
<th class="align-middle text-center">Kolom</th> | |
</tr> | |
</thead> | |
<tbody> | |
@foreach($models as $model) | |
<tr> | |
<td>{{$model->column_name}}</td> | |
</tr> | |
@endforeach | |
</tbody> | |
</table> | |
// PAGINATION LINK, CHECK: https://laravel.com/docs/8.x/pagination#displaying-pagination-results | |
// MENYERTAKAN QUERY STRING SEBELUMNYA, CHECK: https://laravel.com/docs/8.x/pagination#displaying-pagination-results | |
{{ $models->appends(request()->query())->links() }} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment