Search code examples
laravelhtml-selectlaravelcollective

Save name instead of id from select component in laravel collective


I want to save the name of a department in the table employees, in the select component it displays the name but saves the id, so I think the problem is in it.

This is the select component:

{{Form::select('nombre_dep', $departamentos, null, array('class'=>'form-control', 'placeholder'=>'Asignar departamento'))}}

In my controller I have this for returning to the view:

$departamentos = departamento::pluck('nombre_dep', 'id');

In the model for employee I have this for relation:

public function departamentos(){
        return $this->belongsTo('App\departamentos');
}

I expect to save in that field for example: production instead of 1 that could be id of the department


Solution

  • Perform the pluck specifying in the key parameter (the second parameter), the field from which you want to get the value to use in the value attribute of the select.

    $departamentos = departamento::pluck('nombre_dep', 'nombre_dep');
    

    Then when you pass the $departamentos array to the Laravel Collective select(), it will create an <option> element for each array element, using the array key as value attribute and the array value as option tag content.

    {{ Form::select('nombre_dep', $departamentos) }}