Form select with Laravel

1

I have this code working, but I would like to know if I would have a more elegant way of writing the following code in the view, through Laravel's forms:

<div class="row">
    <div class="col-xs-12 form-group">
        <label for="marca_id">Selecione a marca deste produto</label>
        <select class="form-control" name="marca_id" required>
        @foreach($marcas as $marca)            
            <option value="{{$marca->id}}">{{$marca->nome}}</option>
        @endforeach
        </select>
    </div>  
</div>  

I tried it this way:

<div class="row">
    <div class="col-xs-12 form-group">            
    {!! Form::label('marca_id', 'Seleciona a marca deste produto', ['class' => 'control-label']) !!}
    {!! Form::select('marca_id', $marcas, old('marca_id'), ['class' => 'form-control select']) !!}
    </div>
</div>

However, he returned the array in SELECT : {"nome":"Teste"} and did not display the correct values in value .

The create function of the controller:

public function create()
{
    if (! Gate::allows('users_manage')) {
        return abort(401);
    }
    $marcas = MarcaCelular::all('nome');
    return view('celulares.create', compact('marcas'));
}

The model MarcaCelular:

class MarcaCelular extends Model
{
    protected $fillable = [
        "nome"
    ];

    protected $table = "marcas_celulares";

    public function celulares(){
        return $this->hasMany('App\Celular', 'marca_id');
    }

}

The Mobile model

class Celular extends Model
{
    protected $fillable = [
        "modelo", "cor", "marca_id"
    ];

    protected $table = "celulares";

    public function marca_celular(){
        return $this->belongsTo('App\MarcaCelular', 'marca_id');
    }

    public function cor(){
        return $this->belongsTo('App\Cor', 'cor_id');
    }

}
    
asked by anonymous 07.05.2018 / 04:06

1 answer

1

At your% change%:

public function create()
{
    if (! Gate::allows('users_manage')) 
    {
        return abort(401);
    }
    $marcas = MarcaCelular::pluck('nome', 'id');
    return view('celulares.create', compact('marcas'));
}

This method controller (which is contained in pluck and also in class Builder ) makes a Collection associative as follows:

[id] = nome

Following the code example, everything array needs to generate Form::select .

References:

07.05.2018 / 14:42