It's a normal behaviour, you have to include id and foreign key.
https://laravel.com/docs/10.x/eloquent-relationships#eager-loading-specific-columns
I have the following piece of code to retrieve an instance of "Panel" with a single "Flag" associated to it. It is mentioned as "flag_id" in the database.
Panel::with('flag')->find($panelId, ['id', 'name', 'brightness', 'flag_id', 'geo_lat', 'geo_lng'])
This returns:
"id": 2,
"name": "Panel X",
"brightness": 100,
"flag_id": 5, //mentioned twice
"geo_lat": "50",
"geo_lng": "50",
"flag": {
"id": 5, //mentioned twice
"name": "Off",
"filename": "black",
"is_special": 0
}
}
Why is "flag_id" returned? If I leave it out in the columns parameter I get "flag" returned as null. Whats the trick here? Thanks!
@niborocin Unless you provide a list of specific columns to retrieve, Eloquent will retrieve all columns from the database. Since there is a column called flag_id in your panels table, that row will always be included. In your case, you are even specifically telling Eloquent to retrieve that column by including it in the list you pass as the second parameter in the ->find() method call.
You could leave out flag_id from that list, but then of course the relationship won’t load, because the property needs to be set in order for Eloquent to know which IDs to look for when fetching the relevant rows from the subsequent database call.
In other words, the flag_id attribute is needed; you can’t avoid retrieving it. If you don’t want it in your Panel model, you need to manually remove it:
Panel::with('flag')
->find($panelId, ['id', 'name', 'brightness', 'flag_id', 'geo_lat', 'geo_lng'])
->each(fn ($item) => unset($item->flag_id))
;
But why is it so important that the flag_id column be removed from your Panel object? What harm does its presence do?
Please or to participate in this conversation.