Dynamic list in alphabetical order?

Asked

Viewed 499 times

1

Within that array of my dynamic list, its contents are returning in a way disorderly, 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>

1 answer

2


Utilize App\Categoria::orderBy('nome')->get(), although this is not a good recommendation. Should come the die ready to View of Controller, but there’s the way 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>

Recommending

The ideal practice would be to send only the data ready for 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:

  • Perfect, but this coming duplicate has some article or some reading tip where I get more information in my creations

  • @leonardosilva duplicates what? because this code refers to what is in your database, your database has duplicated items?

  • @leonardosilva and then the problem was solved?

  • nor could friend, I put aside for a while, to return to my initial projects, but today I gave continuity to them.

Browser other questions tagged

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