Search code examples
phplaravellaravel-5where-in

How to make Laravel whereIn not sorted automatically


my array from $temp is Array ( [0] => 22 [1] => 26 [2] => 20 [3] => 24 ) or 22|26|20|24

when I use whereIn like this

$robjeks = DB::table('objek')->whereIn('id', $temp)->get();

the result is 20|22|24|26|

it's automatically sorted. I want it's not sorted.

how to make it same like 22|26|20|24?

thanks for your attention.


Solution

  • This has nothing to do with Laravel. Read here first: avoid Sorting by the MYSQL IN Keyword

    Then, to do this, you can use this code:

    $temp = [22, 26, 20, 24];
    $tempStr = implode(',', $temp);
    $robjeks = DB::table('objek')
        ->whereIn('id', $temp)
        ->orderByRaw(DB::raw("FIELD(id, $tempStr)"))
        ->get();
    

    You might be in risk with sql injection in this case, so please sanitize the array of numbers accordingly.

    Ref: Laravel: order by where in