Search code examples
laravellaravel-query-builder

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


Solution

  • you can use orderByRaw such as:

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