Reputation: 375
I have the following scenario:
public function transactions(): HasMany {
return $this->hasMany(Transaction::class);
}
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
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