Home > Mobile >  How to order by using id with firstWhere in laravel
How to order by using id with firstWhere in laravel

Time:05-05

I'm trying to get a list of areas but ordering by id where id = $area_id;

I tried by using firstWhere:

$area_id = 31;
$areas = Area::firstWhere('id', '=', $area_id)->get()->values()->toArray();

dump($areas[0]);

the result of $areas[0] should be the 31th area, but is the first area

^ array:5 [▼
  "id" => 1
  "name" => "オアフ島"
  "area_group_id" => 1
  "created_at" => "2022-04-28T20:22:18.000000Z"
  "updated_at" => "2022-04-28T20:22:18.000000Z"
]

How can I order by "id" where id = $area_id?

CodePudding user response:

You need to use orderByRaw:

$areas = Area::orderByRaw('id = ? desc', [$area_id])->get();

https://laravel.com/docs/9.x/queries#orderbyraw

  • Related