Laravel pluck fields from relations
Asked Answered
H

4

48

I have a Seller object which has a related User. I need to fill a select from LaravelCollective so I need to make something like this:

{!! Form::selectGroup('seller_id', 'Seller', Seller::with('user')->pluck('user.first_name', 'id')->toArray(), null) !!}

The problem is that I cannot take fields from relationships (user.first_name).

How can I do it?

UPDATE

I want to avoid doing this...

<?php 
    $sellers = [];

    Seller::with('user')->get()->each(function ($seller) use (&$sellers) {
        $sellers[$seller->id] = $seller->user->first_name;
    });
?>
Huntley answered 16/11, 2016 at 14:51 Comment(0)
H
99

You can use Laravel's pluck method as:

$sellers = Seller::with('user')->get()->pluck('user.first_name', 'id')
Heatherheatherly answered 16/11, 2016 at 15:49 Comment(1)
Calling pluck after get(), is using collection to filter am I right? So we are doing filtering on php side?Ronda
V
19

try with below solution it's working for me as i am using laravel 8

$sellers = Seller::with('user')->get()->pluck('user.*.first_name')
Vagina answered 9/6, 2021 at 9:2 Comment(0)
W
16

You can achieve it by using join() & pluck() like this:

$s = Seller::join('users', 'sellers.user_id', '=', 'users.id')
          ->pluck('sellers.id', 'users.id')
          ->all();

This would give an array like this:

[
    'seller_id_1' => 'user_id_1',
    'seller_id_2' => 'user_id_2',
    'seller_id_3' => 'user_id_3',
    'seller_id_4' => 'user_id_4',
    'seller_id_n' => 'user_id_n',
];

Hope this helps!

Wingard answered 16/11, 2016 at 15:34 Comment(1)
You have the arguments backwards in your call to pluck(). To get the results that you're suggesting you'd have to call: pluck('users.id', 'sellers.id'). The first arg is the value to pluck, the second arg is the value to use as the array key per plucked value.Pupillary
S
2

Another way to do it is to define what columns you need inside the relationship. It's good if you always need just these columns on the given relationship. Example:

Class Seller extends Model {
    ...

    public function user()
    {
        return $this->hasOne(user::class, 'id')
            ->select('id', 'first_name');
    }
}
Shyster answered 14/5, 2018 at 15:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.