-3

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 the 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');

ReportController.php

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

Report.php

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');
}

I get this error in the network

error in network

When I double-clicked on 500 in the network tab. It open a new tab, I see this error Call to a member function when() on string

error

Mahmoud Khosravi
  • 356
  • 4
  • 9
  • 17

1 Answers1

0

$search is a string from request. You can use when only on Query Builder / Eloquent.

Daniel
  • 2,621
  • 2
  • 18
  • 34