Dynamic list in alphabetical order?

1

Inside this array of my dynamic list , its content is returning in a disordered way, how do I put it alphabetically?

<div class="form-group">
        <label for="nome">Categoria do Produto</label>
        <select id="categoria_id" name="categoria_id" class="form-control">
            <option value="">Selecione</option>

            @foreach (App\Categoria::all() as $categoria)
                <option value="{{ $categoria->id }}">{{ $categoria->nome }}</option>
            @endforeach

        </select>
</div>
    
asked by anonymous 17.01.2017 / 00:48

1 answer

2

Use App\Categoria::orderBy('nome')->get() , although this is not a good recommendation. You should see the data ready for View of Controller , but that's how it should be.

<div class="form-group">
    <label for="nome">Categoria do Produto</label>
    <select id="categoria_id" name="categoria_id" class="form-control">
        <option value="">Selecione</option>

        @foreach (App\Categoria::orderBy('nome')->get() as $categoria)
            <option value="{{ $categoria->id }}">{{ $categoria->nome }}</option>
        @endforeach

    </select>
</div>

The ideal practice would be to send only the ready-made data to your View :

Controller

public function exibe()
{
    $data['categories'] = \App\Categoria::orderBy('nome')->get();
    return view('view1', $data);
}

View

<div class="form-group">
    <label for="nome">Categoria do Produto</label>
    <select id="categoria_id" name="categoria_id" class="form-control">
        <option value="">Selecione</option>

        @foreach ($categories as $categoria)
            <option value="{{ $categoria->id }}">{{ $categoria->nome }}</option>
        @endforeach

    </select>
</div>
This is an example, dummy data

References:

17.01.2017 / 00:55