skip to Main Content

I need to display accounts as headings with a numerous transactions listed under each account in Laravel. I have two tables: one for accounts and another for transactions. The goal is to retrieve a limited number of transactions for each account efficiently.

Currently, I use the following relation in the Account model:

$this->hasMany('AppModelsTransaction', 'account_id', 'id');

The query I’m using is:

$transactions = Account::with('transactions')->where('store_id', $store_id)->paginate(5);

This gives me pagination for the accounts table, but what I really need is to display the account names and load transactions for each account in chunks, as loading too many transactions at once is slow when the transaction count is large.

I’ve been searching for a more efficient solution but haven’t found one yet.

2

Answers


  1. $transactions = Transaction::whereHas('account' , fn($query) use($storeId) { 
            $query->where('store_id', $storeId)
        })
        ->with('account')
        ->paginate(50)
    

    You can directly get the transactions like this and for the account name on the blade page use this

    @foreach($transactions as $transaction)
        {{ $transaction->account->name }}
    @endforeach
    
    Login or Signup to reply.
  2. Just retrieve the accounts informations without the transactions

    $accounts = Account::query()->where('store_id', $store_id)->paginate(20);
    

    Then for each account fetch their transactions with infinity scroll on demand in a separate route.

    $transactions = Transaction::where('account_id', $accountId)->paginate(20);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search