Skip to content
Advertisement

Laravel blade multiple select. How to select records in the pivot table?

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()?

Advertisement

Answer

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…

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement