If you ever used the pluck
eloquent methods, you can see that, it will get a set of key
or key => value
columns, if you pass the second parameter
1$users = User::pluck('name', 'id'); 2 3// will return 4Illuminate\Support\Collection { 5 all: [ 6 1 => 'Oussama', 7 2 => 'Nuno', 8 // ... 9 ]10}
But what about relationship
columns? Did we need to make something like this
1$users = User::with('profile')->get(); 2$address = []; 3 4foreach($users as $user) { 5 $address[] = [ 6 $user->id => $user->profile->pluck('address'), 7 ]; 8} 9 10// will return11array:2 [12 1 => 'Some Address',13 2 => 'Another Address',14 // ...15]
I don't think the above code, is a good idea! Instead, we can use:
1$address = User::with('profile')->pluck('profile.address', 'id'); 2 3// will return 4Illuminate\Support\Collection { 5 all : [ 6 1 => 'Some Address', 7 2 => 'Another Address', 8 // ... 9 ]10}
If you want to get more than columns, you may check Our previous article about pluck method