Laravel - Assign a value in an option of a select!

0

Hello (I'm just learning),

I need in the value to assign the value of the id. Example: <option value="{{$idcategoriacuenta}}">{{$categoria}}</option>

The problem is in the array () I do not know how to send the value of the category and the idcategoriacuenta

I have the following code:

In the Model :

class Cuentasconcategoria extends Model
{
protected $table='view_cuentasconcategoria';
public $timestamps=false;
protected $fillable =[
  'idcategoriacuenta',
  'cuenta',
  'categoria',
];
}

In the driver

public function create(){
 $categoriacuenta=Cuentasconcategoria::all();
 $attributes = array();
 foreach ( $categoriacuenta as $v ) {
    if ( !isset($attributes[$v->cuenta]) ) {
        $attributes[$v->cuenta] = array();
    }
    $attributes[$v->cuenta][$v->categoria] = $v->categoria;
 }
return view ('inventario.articulo.create',
["attributes"=>$attributes]);
}

In the view:

<select>
  @foreach ( $attributes as $key => $cuenta)
  <optgroup label="{{$key}}">
    @foreach ( $cuenta as $categoria )
        <option value="{{$categoria}}">{{$categoria}}</option>
    @endforeach
  </optgroup>
  @endforeach
    </select>

If the previous code works I just need to assign the value with the id

The result of the above:

    
asked by Interes Ciencia 20.11.2017 в 05:57
source

2 answers

1
$categoriacuenta=Cuentasconcategoria::all();

luego en el foreach de la vista 

@foreach($categoriacuenta as $categoriacuenta)

 <option value="{{$categoriacuenta->idcategoriacuenta}}">{{$categoriacuenta->categoria}}</option>

@endforeach
    
answered by 20.11.2017 / 13:46
source
0

It seems that your model and controller are fine, the mofidication requires the view and it is logical since the view is responsible for everything related to the interface (the how to show the client).

Make the following modification:

<select>
  @foreach ( $attributes as $key => $cuenta)
  <optgroup label="{{$key}}">
    @foreach ( $cuenta as $categoria )
        <option value="{{$categoria->idcategoriacuenta}}">{{$categoria}}</option>
    @endforeach
  </optgroup>
  @endforeach
    </select>

This is because the element has the attribute "value" that corresponds to the value that the select will take, while its child node is what will be displayed visually.

Sometimes you can have your value and your child node the same value, but usually they will be different.

<option value="{{$categoria->idcategoriacuenta}}">{{$categoria}}</option>

The first value will be numeric and the second one a string. So you can change the values you want to show of your $ category object according to your needs.

    
answered by 20.11.2017 в 15:18