baguus

Multiselect dropdown on belongstomany

Posted 1 year ago by baguus

Hi everyone. I'm.. complicating but: I want to populate a multi select dropdown with users that have a specific user role I have 5 tables (users, role_user, roles, companies and company_user)

Model relations

App\User:

public function roles()
    {
        return $this
            ->belongsToMany('App\Role')
            ->withTimestamps();
    }


    public function companies()
    {
        return $this
            ->belongsToMany('App\Company')
            ->withTimestamps();
    }


App\Role:
    public function users()
    {
        return $this
            ->belongsToMany('App\User')
            ->withTimestamps();
    }


App\Companies:
    public function users()
    {
        return $this->belongsToMany('App\User');  // with user_role ??
    }

CompaniesController

public function edit(Request $request, $id) {

$company = Company::findOrFail($id);

$users = User::where('role_id',4)->pluck('username')->all(); // no role_id column
$users = User::pluck('username','id')->all();  // returns all without selected

return view('companies.edit', compact(['company','users']));
}

public function update(Request $request, $id) {
    /* TODO */
}

Edit view


{!! Form::select('users[]', $users, null, ['class' => 'form-control', 'multiple' => 'multiple']) !!}


Do I need to create another connecton between companies and roles? I need to display only the users that have a specific user role.

Subquestion: Is there a simple way to concatenate First name + Last name instead od username in the dropdown?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.