Fill a select in Laravel

3

I have a problem trying to fill a select with data from the database, with laravel 5.6

In my controller I have the following code:

public function index()
{
    $roles=roleUser::pluck('id_role','nombre');

    return view('auth.register',compact('roles') );
} 

in my view I have it this way

<select id="id_role" name="id_role" class="form-control">
       <option>------Seleccionar------</option>
       @foreach($roles as $role)
       <option value="{{ $role['id_role'] }}">{{ $role['nombre'] }}</option>
       @endforeach
</select>

But when you render it does not show me any data just like this:

<select id="id_role" name="id_role" class="form-control">
     <option>------Seleccionar------</option>
     <option value=""></option>
     <option value=""></option>
     <option value=""></option>
     <option value=""></option>
     <option value=""></option>
     <option value=""></option>
     <option value=""></option>
     <option value=""></option>
 </select>
    
asked by ALVARO ROBERTO BACARREZA ARZAB 04.05.2018 в 03:27
source

1 answer

2

We start from the basis that the model roleUser has data. The problem is generated after using the pluck method ( Official Documentation ), this method returns you a collection in key / value format. That is, if we have the following data we would obtain:

$data = collect([
    ['id_role' => '1', 'nombre' => 'usuario'],
    ['id_role' => '2', 'nombre' => 'administrador'],
]);

$roles = $data->pluck('nombre', 'id_role');

$roles->all(); // ['1' => 'usuario', '2' => 'administrador']

Notice that the way I did the pluck is as follows: pluck('nombre', 'id_role') , since the first parameter gets the values and the second the keys to which you assign them. That's your first fault, you do the assignment in reverse.

Next, the correct way to print a set of keys / value would be as follows:

@foreach( $roles as $key => $value )
   <option value="{{ $key }}">{{ $value }}</option>
@endforeach
    
answered by 04.05.2018 / 10:04
source