⌘K
Noting Found

View all related articles

The Easiest Way To Pluck Relation Model Attributes In Laravel.

Snippets 1 min read

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 return
11array: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

Related Tags

About the Author

Oussama's Profile Picture
Oussama
Full Stack Web Developer | Technical Writer

Oussama is an experienced full-stack web developer with a strong focus on Laravel. He's passionate about crafting web applications with Filament and the TALL Stack. With 8+ years of experience, and he's a dedicated open-source contributor.

Comments

Join our newsletter

Subscribe to Our Newsletter and never miss our offers, latest news, Articles, etc.

We care about the protection of your data. Read our Privacy Policy.