'Is it possible to query from eger loading with where clause?

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


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 josezenem