0

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?

Thank you so much in advance!

SleepWalker
  • 613
  • 1
  • 12
  • 39
  • Does this answer your question? [Laravel pluck fields from relations](https://stackoverflow.com/questions/40635146/laravel-pluck-fields-from-relations) – miken32 Nov 18 '20 at 19:44
  • 1
    `pluck('profile.first_name');` – miken32 Nov 18 '20 at 19:45
  • I think you need [only](https://laravel.com/docs/8.x/collections#method-only) instead of pluck – apokryfos Nov 18 '20 at 20:05
  • thanks @miken32! Also I'm wondering is possible to add the last name inside the pluck? because what I need to show in the select field is the first_name and last_name – SleepWalker Nov 18 '20 at 20:08
  • `pluck()` is for pulling a single column out of the results. You may be looking for `get()` instead, or `only()` as suggested above. – miken32 Nov 18 '20 at 20:10

1 Answers1

0

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.

mmabdelgawad
  • 2,385
  • 2
  • 7
  • 15