Alan Alan - 1 year ago 226
PHP Question

Laravel pluck fields from relations

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?


I want to avoid doing this...

$sellers = [];

Seller::with('user')->get()->each(function ($seller) use (&$sellers) {
$sellers[$seller->id] = $seller->user->first_name;

Answer Source

You can use Laravel's pluck method as:

$sellers = Seller::with('user')->get()->pluck('user.first_name', 'id')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download