35

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
  • 63,488
  • 15
  • 64
  • 88
Alan
  • 2,319
  • 3
  • 25
  • 46

3 Answers3

71

You can use Laravel's pluck method as:

$sellers = Seller::with('user')->get()->pluck('user.first_name', 'id')
Amit Gupta
  • 14,778
  • 2
  • 31
  • 49
11

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
  • 10,919
  • 5
  • 35
  • 41
  • 2
    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
  • 369
  • 1
  • 14