Creating a drop down list in laravel to select a users role - laravel

4.6k Views Asked by At

I am creating a website using laravel and I have a form to create a new users and within it i need an option to display a way to select a users role, i would like to do this in the form of a drop down list but I'm having difficulty figuring it out.. so far I have this (see below my create.blade.php), but it is not displaying the data from the three roles i have in the table in the DB, (these are admin,instructor and student).

<div class="form-group">
   <label for="role">Role</label>
   <select name="roles[]" class="form-control">
   @foreach($roles as $role)
     <ul class="dropdown-menu" role="menu">
     {{ $role }}
     </ul>
   @endforeach 
   </select>
</div>

Below is my form, I am new to laravel so just trying to learn to better myself, any help is much appreciated :)

enter image description here

2

There are 2 best solutions below

1
Foued MOUSSI On

If you're using native HTML select, you may use

<div class="form-group">
   <label for="role">Role</label>
   <select name="roles[]" class="form-control">
   @foreach($roles as $role)
     <option value="{{ $role->id }}"> {{ $role->nameOrWhatever }} </option>
   @endforeach 
   </select>
</div>
0
Tiago Martins Peres On

In your UserController

/**
 * Show the form for creating a new user
 *
 * @param  \App\Role  $model
 * @return \Illuminate\View\View
 */
public function create(Role $model)
{
    return view('users.create', ['roles' => $model->get(['id', 'name'])]);
}

then, in your create.blade.php

<select name="role_id" id="input-role" required>
    <option value="">-</option>
    @foreach ($roles as $role)
        <option value="{{ $role->id }}" {{ $role->id == old('role_id') ? 'selected' : '' }}>{{ $role->name }}</option>
    @endforeach
</select>

This will get you the desired

Laravel dynamic dropdown