4
votes

I have 2 table which name incomes and expenses and I want to show all the data in one view with laravel pagination. For this, I Merged two array with array_merge().

$incomes = Income::where('user_id', Auth::User()->id)->get()->toArray();
$expenses = Expense::where('user_id', Auth::User()->id)->get()->toArray();
foreach ($incomes as $key => $value) {
    $incomes[$key]['type'] = 'income';
}

foreach ($expenses as $key => $value) {
    $expenses[$key]['type'] = 'expense';
}

$results = array_merge($incomes, $expenses);

How can I paginate this $results?

1
What are you trying to achieve with your pagination? is it solely to make it easier to navigate the array of incomes and expenses? Or are you trying to optimize the page load times too?Spholt
Laravel helps you best if you supply the Eloquent query result to their paginator, but it does allow you to create a manual paginator that can handle a simple array. Did you have a look here? laravel.com/docs/6.x/pagination#manually-creating-a-paginatorxyz
@xyz Yes, I see it. But basically I want to know that is there any way to use default pagination instead of creating it manually?nayeemdev

1 Answers

6
votes

You can do this in two ways:

  1. Laravel's built in manually creating a paginator functionality.
  2. Get the results from tables using UNION.

Using UNION

$incomes = Income::where('user_id', Auth::User()->id);
$data = Expense::where('user_id', Auth::User()->id)->union($incomes)->paginate(10);

For manually creating a paginator, please see https://laravel.com/docs/6.x/pagination#manually-creating-a-paginator

Add the following to Income Model

protected $appends = ['type'];

public function getTypeAttribute()
{
    return 'Income';
}

Add the following to Expense Model

protected $appends = ['type'];

public function getTypeAttribute()
{
    return 'Expense';
}

This will add the type key in the query results.