ThurstonLevi
ThurstonLevi

Reputation: 859

Laravel WhereIn keep order used by array

So I'm getting some items out my database to use in a dropdown. I wish to have the dropdown show the items in the order these are entered so for example i want to have items ordered as 2,1,3. When i render the result the results are sorted by id and not in the order i desire:

<?php

namespace App\View\Components;

use App\Models\JobState;
use Illuminate\View\Component;

class StatusDropdown extends Component
{
    public $states;

    public function __construct()
    {
        $this->states = JobState::whereIn( 'id', [4, 5, 10, 3, 11] )->get();
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.status-dropdown');
    }
}

and here is my view:

<select name="status" class="pl-10 block w-full shadow-sm sm:text-lg bg-gray-50 border-gray-300 focus:ring-primary-500 focus:border-primary-500 rounded-md">
    @foreach( $states as $state )
        <option value="{{ $state->id }}">{{ $state->value }}</option>
    @endforeach
</select>

How can i do this without manually getting them one at a time or adding a new column?

thanks

Upvotes: 5

Views: 1896

Answers (2)

ThurstonLevi
ThurstonLevi

Reputation: 859

I worked it out. I replaced my constructor with this:

    public function __construct()
    {
        $order = [4, 5, 10, 3, 11];
        $states = JobState::whereIn( 'id', $order )->get();
        $this->states = $states->sortBy(function( $model ) use ( $order ) {
            return array_search( $model->getKey(), $order );
        });
    }

Upvotes: 1

Thai Nguyen Hung
Thai Nguyen Hung

Reputation: 1232

you can use orderByRaw such as:

JobState::whereIn( 'id', [4, 5, 10, 3, 11])->orderByRaw('FIELD(id, 4, 5, 10, 3, 11)')->get();

Upvotes: 8

Related Questions