简体   繁体   中英

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

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:)

在此处输入图像描述

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>

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 动态下拉

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM