1

I want to sort a collection by id, where id`s are stored in a custom array.

I am doing something like this:

// get the slides images
$allSlides = DB::table('homepage_slides')->paginate(10);
// slideOrderSetting is a json, storing the order for slides [{"id":4},{"id":1},{"id":2},{"id":3},{"id":5},{"id":6}]
$slideOrder = json_decode($slideOrderSetting, true); 

// sort the slides
$slides = array();
foreach ($slideOrder as $order){
    foreach ($allSlides as $slide){
        if((int)$order['id'] === (int)$slide->SlideID){
            array_push($slides, $slide);
            break;
        }
    }
}

// get the slide array sorted
return $slides;

The array slides get sorted, but....the problem is that i loose the pagination and other stuff from $allSlides collection.

How can i sort the slides collection using the custom array with id`s ?

calin24
  • 905
  • 3
  • 21
  • 43

1 Answers1

2

Get all IDs from your $slideOrderSetting:

$slideOrderArray = json_decode($slideOrderSetting, true);
$slideOrderIDs = collect($slideOrderArray)->pluck('id')->toArray()

About pluck() method

Then get slides:

$slides = DB::table('homepage_slides')
    ->orderByRaw(DB::raw('FIELD(id, '.implode(', ', $slideOrderIDs).')'))
    ->paginate(10)

or

$slides = DB::table('homepage_slides')
    ->whereIn('id', $slideOrderIDs)
    ->orderByRaw(DB::raw('FIELD(id, '.implode(', ', $slideOrderIDs).')'))
    ->paginate(10)
Andrii Lutskevych
  • 1,349
  • 13
  • 23