Laravel 6
How to search with select 2 in laravel and ajax?
MahmoudKhosravi
I'm trying to load into Select2 the selected value extracted from the DB. Id values are saved in a JSON field that contains the id values or the field '*' that I manage as 'All'.
I want to search first_name
and last_name
in users table.
AJAX
<script>
$(document).ready(function() {
$('#plaintiffId').select2({
ajax: {
url: '{{ route('admin::reports.plaintiffId') }}',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
first_name: item.user.first_name,
last_name: item.user.last_name,
}
})
};
},
cache: true
}
});
</script>
web.php
Route::get('reports/plaintiffId', 'Admin\ReportController@plaintiffId')->name('reports.plaintiffId');
Controller
public function plaintiffId(Request $request, $term)
{
$data = [];
if($request->has('q')){
$search = $request->q;
$data = $search->when($term, function ($query) use ($term){
return $query->whereHas('plaintiff', function ($query) use ($term) {
$query->where('first_name', 'like', "%{$term}%");
$query->orWhere('last_name', 'like', "%{$term}%");
});
});
}
return response()->json($data);
}
Model
public function scopeSearch($query, $term)
{
return $query->when($term, function ($query) use ($term){
return $query->whereHas('plaintiff', function ($query) use ($term) {
$query->where('first_name', 'like', "%{$term}%");
$query->orWhere('last_name', 'like', "%{$term}%");
});
});
}
public function plaintiff()
{
return $this->belongsTo(User::class, 'plaintiffId');
}
When I double-clicked on 500 in the network tab. I see this error Call to a member function when() on string
I get this error in network
Posté il y a 1 an
CinquièmeDimension
Hi,
I don't think you send the $term right. If you send it like this, you shouldn't make it a parameter.
If you want to make it a parameter you have to declare the parameter in the route.
The easyest way, is not to make this
public function plaintiffId(Request $request, $term){
[...]
}
but to make it like this
public function plaintiffId(Request $request){
$term = $request->input('term', false);
[...]
}
Posté il y a 1 an
Vous ne pouvez pas répondre à ce sujet.