Reputation: 93
I am using Laravel, and I have a projects table and a users table. Each project can have multiple users. I have set up a project_user pivot table.
I am trying to create a multiselect box that lists all users, and has the users currently assigned to the project selected. Here is my ProjectsController function that creates the view.
public function edit($id)
{
$project = Project::findOrFail($id);
$users = User::lists('name','id');
return View::make('projects.edit', compact('project','users'));
}
And here is the relevant blade form:
{{ Form::select('user_id[]', $users, ??? , array('multiple')) }}
Where I think ??? should be an array of user_ids associated with the project. Can I get that from
$project->user...something here?
Or, do I need to create the array in function edit()?
Upvotes: 3
Views: 2863
Reputation: 105
$assignedUserIds = $project->users()->lists('id');
to
// I used in laravel 5.7
$assignedUserIds = $project->users()->pluck('id');
Upvotes: 0
Reputation: 96
Accepted answer is right except on Laravel 5.2 I had to do ->toArray():
$assignedUserIds = $project->users()->lists('id')->toArray();
to get this to work with Form::select.
I would have commented original answer, but I don't have enough reputation.
Upvotes: 0
Reputation: 153010
You are almost there. First make sure you have the correct relationship defined in your project model
public function users(){
return $this->belongsToMany('User');
}
Now to get the ids of all assigned users:
$assignedUserIds = $project->users()->lists('id');
And just pass that to the view...
Upvotes: 2