Home > OS >  Laravel eloquent without() in nested relationship
Laravel eloquent without() in nested relationship

Time:05-31

I am trying to exclude a few relations from my API call.

Right now I'm returning the records as following:

return response()->json(Ticket::where('status_id', '!=', 5)->get());

In the ticket model I have a belongsTo relation with customer. In the customer model I have a hasOne relation with Address.

Now, I have included the address in the customer model, and the customer in the ticket model usin $with.

I want to get the customer with the ticket, but not the address. I tried using the without function as followed: Ticket::where('status_id', '!=', 5)->without(['customer.address'])->get().

This is not working, however the following does work: Ticket::where('status_id', '!=', 5)->without(['customer'])->get() I do get the ticket without any relations.

I assumed the first function would work, considering this also works in the with() function, but it does not.

CodePudding user response:

To remove the relation address while keeping the address relation in the $with attribute of the customer class, use this:

Ticket::where('status_id', '!=', 5)->with(['customer' => function($customer){
    $cutomer->without(['address']);
}])->get()

But I suggest you remove the address from the $with attribute or you will end up with more without(['address']) than with('address') if you remove it.

CodePudding user response:

It should work provided there's no typo in the relation name (like address instead of addresses).

Another approach - try the following

return response()->json(
    Ticket::with('customer', fn($query) => $query->without('address'))
        ->where('status_id', '<>' 5)
        ->get()
);

I think even this should work (without typos in relation name)

return response()->json(Ticket::without('customer.address')->where('status_id', '<>' 5)->get());

This should remove/unset address relationship from customer

  • Related