Home > database >  Laravel WhereIn keep order used by array
Laravel WhereIn keep order used by array

Time:06-20

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" >
    @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

CodePudding user response:

you can use orderByRaw such as:

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

CodePudding user response:

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 );
        });
    }
  • Related