skip to Main Content

Originally I had a single tab in the page that displayed the data as a table:

$data = MyModel::paginate(100);

Then, I needed to split the data to 2 different tabs in the page with different filters:

$tab_1_data = MyModel::where('column', 'some_value');

$tab_2_data = MyModel::where('column', 'some_other_value');

Is it possible to get the paginated data for the two tabs using a single query? Or I will have to do 2 queries in this case:

$tab_1_data = MyModel::where('column', 'some_value')->paginate();
$tab_2_data = MyModel::where('column',  'some_other_value')->paginate();

Because these 2 queries may slow down the page loading time

2

Answers


  1. $data = MyModel::paginate(100);
            
    $tab1 = array_slice($data->items(), 0, $data->total() / 2);
    $tab2 = array_slice($data->items(), $data->total() / 2);
    
    
    Login or Signup to reply.
  2. For a given collection, we can use the Partition Method to split a collection based on a truth test. This, however, would not work if there is overlap between the two models. If this is the case, your best option is using the Filter method.

    You can get your initial collection by getting all records that satisfy all total requirements:

    $records = YourModel::where(**your conditions**)->get();
    

    Then either filter down or partition into multiple collections based on your conditions.

    [$first, $second] = $records->partition(function ($record) {
        return $record === 'this_is_the_truth_test';
    });
    

    These individual collections can then be paginated to display as you wish.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search