Form select with Laravel

Asked

Viewed 1,300 times

1

I have this code working, but I wonder if there would be a more elegant way to write the following code in the view, through the Laravel formats:

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

But it returned the array like this 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 Marcacelular model:

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

    protected $table = "marcas_celulares";

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

}

The Cellular 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');
    }

}
  • Set to $marks = Cellmark::all('name')->Pluck('name','id');

1 answer

1


In his controller alter:

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

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

[id] = nome

following the example of the code, all that the Form::select needs to generate the <select>.

References:

  • 1

    Perfect friend, that’s what I wanted. Using the Laravel Form the code gets much cleaner. Thank you from the heart!

  • Just my comment in detail. It’s something similar to pure PHP array_column.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.