I am using this code to obtain data.
$user = User::where('active', 1)->with(['spots:spot_name,spot_uid'])->get();
This is working great! It gets the relationship and outputs the data.
However the data looks like this.
user_uid: 5
spots: {spot_name: 'backend'}
description: "Test user works in helpdesk"
department: "9"
It is showing all the data I need, but I would like for the spot_name to not be in its own child json array and just have the spot_name be spots. Like this:
spots: "backend"
I know this is because it obtains the 2 columns and then I have one hidden.
Is this not possible, or am I just going about it the wrong way? Any information would be great.
CodePudding user response:
You can format output with collections:
$user->map(function ($x) {
$arr = $x->toArray();
$arr['spots'] = $arr['spots'][0]['spot_name'];
return $arr;
});
And then out this user.
CodePudding user response:
You can do it
User::where('active', 1)->withCount(['spots as spot_name' => function ($q) {
$q->select('spot_name');
}]);
output
{
...
spot_name: 'backend'
}