Sir George
Sir George

Reputation: 433

Fetching all users in laravel 5.2

I am trying to fetch all the users in my application so as to pick the user name or id in a select form, but I have not been able to achieve this after a long struggle. My MessageController that retrieves the messages is:

public function getMail(){
        $message = Message::orderBy('created_at', 'desc')->get();

$pple = User::where('id', '!=', Auth::id())->pluck('name', 'id')->all();
    var_dump($pple);

            return view('mail', array('user' => $pple))->with('messages', $message, 'users',$pple );
    }

My view that I want to render the users is:

<div>
<select id="recipient">
   <option>{{$pple->name}}</option>
       </select>
          </div>

I have really tried doing this to help me pick up a user id or name to use in my messaging system.I would appreciate if someone helped me with this

Upvotes: 1

Views: 1083

Answers (2)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

You should get your users then pluck to get the result:

$messages = Message::orderBy('created_at', 'desc')->get();

$users = User::where('id', '!=', Auth::id())->pluck('name', 'id');

and return

return view('mail')->with(compact('messages', 'users'));

Then use it this way in your view

<select name="recipient" id="recipient">
    @foreach($users as $id => $name)
        <option value="{{ $id }}">{{ $name }}</option>
    @enforeach
</select>

Don't forget to add a name to your select.

Upvotes: 2

Loek
Loek

Reputation: 4135

In your view, this should work

@foreach($pple as $userId => $userName)
    <option value="{{ $userId }}">{{ $userName }}</option>
@endforeach

Upvotes: 1

Related Questions