Laravel Pluck Concat Relations

436 Views Asked by At

Im using laravel 8 to my project, trying to pluck data from a Model

    $user = Users::with('media')->get()->pluck('media.title', 'id')->all();

I got the Output

    {
     "sample": 1,
    }

My expected output,Looking for the value combine a column from media table and column from user table

   {
     "media.title + user.name": id,
   }
1

There are 1 best solutions below

0
On

To my knowledge this isn't possible with pluck directly. You have 2-3 options the way I see it:

Either make an accessor in your User model which concatenates the user name and the media title, something like:

public function getNameWithMediaAttribute()
{
    return $this->name . ' + ' . $this->media->title
}

Which you then pluck with ->pluck('nameWithMedia') after your query.


Or you can pull them the way you did with $user = Users::with('media')->get(); and map over the result to return the format you want. Something like:

$users = User::with('media')->get()->map(function($user) 
{
    return [$user->media->title . ' + ' . $user->name => $user->id];
})->collapse();

Don't forget about the ->collapse() part.


You could also make a query which gathers that data under one field and then you pluck it after pulling it from the database. But my SQL-fu isn't good enough to do that easily.