Pluck the values from WITH Eloquent in Laravel

435 views Asked by At

I have a dropdown box that shows only the user with collector and borrower's role. Here's my code

public function create()
{
    $users = User::whereHas('roles', function ($q) {
                $q->where('roles.name', '=', 'collector')->orWhere('roles.name', '=', 'borrower');
            })
            ->with('profile')
            ->get()
            ->pluck('name','id');

    return view('dashboard.documents.create', compact('users'));
}

this code is fine but what I what to pluck is the column first_name, last_name and user_id from 'profile'. How can I achieve that?

1

There are 1 answers

2
mmabdelgawad On

You do one of these

$users = User::whereHas('roles', function ($q) {
             $q->where('roles.name', '=', 'collector')->orWhere('roles.name', '=', 'borrower');})
            ->with('profile')
            ->select('name','id')
            ->get();

Or

$users = User::whereHas('roles', function ($q) {
             $q->where('roles.name', '=', 'collector')->orWhere('roles.name', '=', 'borrower');})
            ->with('profile')
            ->get(['name','id']);

Both ways will return a collection with related models each model record will has the selected columns, if you want to convert it to an array you can add ->toArray() after the two ways and it will convert the collection to array.