Reputation: 33
I am using Laravel 8.
Assume the show() function is called in a Controller, providing me with a specific Location. The goal is to return a view with that location, but adding relation data to the $location variable beforehand. Since there already is a location but it is missing some data, I call the load function to lazy eager load the relation. Also, I need the soft Deleted customers as well, thus using a closure like so:
public function show(Location $location)
{
$location = $location->load([
'customers' => function($query) {
$query->withTrashed();
}]
);
return view('location.EditLocationView', ['location' => $location]);
}
Now, I face a problem. I only need the customers names stored inside of the $location variable, preferably in an array "['James', 'Christian' ... ]"
How do I do that? The code should probably look like something somilar to this:
public function show(Location $location)
{
$location = $location->load([
'customers' => function($query) {
$query->withTrashed()->select('names')->toArray();
}]
);
return view('location.EditLocationView', ['location' => $location]);
}
And $location should look like this:
$location = name: .. lat: .. lng: .. customers: ['James', 'Christian' ... ]
Thanks for your help.
Upvotes: 3
Views: 1555
Reputation: 64466
The problem with eager load is you can't select only name column you will need to select the foreign key also in order to properly map the data with location like
$query->withTrashed()->select(['location_id','names'])
If its a single $location
record then you could also perform lazy load because it will fire one query (same as above eager load case) and then you can store customers name in another variable and pass it to view.
$customers = $location->customers()->withTrashed()->pluck('name')->toArray();
Upvotes: 3