Čamo's avatar
Level 3

How to remove relation.relation from result?

I need to get model with its relation, but this relation pull their relations which I dont want to have in result. So I tried to use Model::witout() where I used dot notation like in with() clasuse. The code looks like:

$receipt = Receipt::where('id', '=', $receiptId)
    ->with(['company', 'currency', 'customer', 'receiptLink', 'receiptPoint'])
    ->without(['customer.receipts'])
    ->first();

As you can see I need to remove customer.receipts relation. But it is still there. How can I remove receipts from result?

0 likes
11 replies
tisuchi's avatar

@Čamo Have you tried this?

$receipt = Receipt::where('id', '=', $receiptId)
    ->with(['company', 'currency', 'receiptLink', 'receiptPoint',
        'customer' => function ($query) {
            $query->select('id', 'name'); // Or whatever fields you need from the customer
        },
    ])->first();

2 likes
Čamo's avatar
Level 3

I dont underastand. It does not work at all. Only if I remove customer from with() clause. But how?

1 like
Čamo's avatar
Level 3

I really dont understand. Also if I try this

Customer::where('id', '=', $receipt->customer_id)->without('receipts')->first();

it returns entity with receipts. What is going on here?

1 like
krisi_gjika's avatar

@Čamo does you Customer model have a $with = ['receipts']?

Čamo's avatar
Level 3

@krisi_gjika No look at my next comment. There is something in $appends which loads all the receipts. How can I remove $appends field from result?

Čamo's avatar
Level 3

It seems is is bacause $appends array contains accessor named "receipts_parsed" which loads all the receipts and returns parsed value. How can I remove the accessor to be loaded if it is mentioned in $appends array?

1 like
krisi_gjika's avatar

@Čamo don't mention it in the $appends array? Normally appends/attributes should not load/request relations

2 likes
Čamo's avatar
Level 3

@krisi_gjika I can not remove it from $appends. Other code can need it. How to disable $appends field for one request?

krisi_gjika's avatar

@Čamo accessors can be used even if they are not in the $appends array. (as long as they are public) All appends does is ALWAYS include an accessor in the model, it's up to you to decide if you want that accessor to always be included or not.

1 like
Čamo's avatar
Level 3

@krisi_gjika I am not the only one who write the code. I found makeHidden() which works but it is not exactly what I want :(

Please or to participate in this conversation.