i got the result from this query:
$loan=Loan::where('user_id',auth()->user()->id)->with('customer')->orderByDesc('created_at')->paginate(10);
BUt when i try to retrive same data as:
$loan = Loan::where('user_id', auth()->user()->id)->with(['customer'=> function ($query) use($search){
$query->where('cname', $search);
}])->orderByDesc('created_at')->get();
query return collection with customer.
through the error as :attempt ro read property on null after following code on blade view
@forelse ($loan as $loans)
<tr>
<td>{{ $loans->customer->cname }}</td>
<tr>
@endforeach
CodePudding user response:
so basically you are querying those customer records which are filtered out from customer table. To fix this filter out all records from Loan model where your sub query(i.e. customer) do not match search criteria.
$loan = Loan::where('user_id', auth()->user()->id)->with(['customer'=> function ($query) use($search){
$query->where('cname', $search);
}])
->whereHas('customer', function($query) use($search){
$query->where('cname', $search);
})
->orderByDesc('created_at')->get();
CodePudding user response:
You can use ->whereHas('customer', function()
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
You would still keep ->with('customer')->whereHas('customer',
You keep the ->with( to eagerload, but filter with whereHas