44

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;
    });
?>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Alan
  • 2,559
  • 4
  • 32
  • 53

4 Answers4

93

You can use Laravel's pluck method as:

$sellers = Seller::with('user')->get()->pluck('user.first_name', 'id')
Amit Gupta
  • 17,072
  • 4
  • 41
  • 53
  • Calling pluck after get(), is using collection to filter am I right? So we are doing filtering on php side? – JEX Jan 03 '23 at 22:11
17

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

$sellers = Seller::with('user')->get()->pluck('user.*.first_name')
dazed-and-confused
  • 1,293
  • 2
  • 11
  • 19
Ankita
  • 340
  • 2
  • 8
15

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!

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
  • 3
    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. – Soulriser Dec 31 '17 at 21:10
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');
    }
}
Vali Munteanu
  • 469
  • 3
  • 15