Laravel Collection Macro Filter by Today

I have the following scenario:

  1. A businesses table whose model has transactions as:
    public function transactions(): HasMany {
        return $this->hasMany(Transaction::class);
    }
  1. A transactions table (transactions belong to a business) - has an id, amount and timestamp columns.

I am displaying all the businesses in a blade view with their transactions count and value. Now I want to filter the transaction count and value by today's date. I have seen the best way is to do a Collection Macro. Here is what I have so far in App Service Provider (which is not working):

Collection::macro('filterByToday', function ($value) {
     return $this->filter(function ($value) {
         return $value->created_at === Carbon::today(); 
     });
});

How can I write this macro such that in blade I can loop through all the businesses displaying this transactions like:

@foreach($businesses as $business)
   Count: {{ $business->transaction->filterByToday()->count() }}
   Value: {{ $business->transaction->filterByToday()->sum('amount') }}
@endforeach

Upvotes: 0

Views: 644

Answers (1)

IGP
IGP

Reputation: 15786

Your macro should not receive any arguments and be defined in the boot method of a ServiceProvider class.

If you're using a custom ServiceProvider class, make sure it is registered in the $providers array in config/app.php

# AppServiceProvider
public function boot()
{
    Collection::macro('filterByToday', function () { // <-- 0 arguments
        return $this->filter(function ($value) {
            return $value->created_at === Carbon::today(); 
        });
    });
}

Upvotes: 0

Related Questions