User::with('userPayment')->get() returns a Collection (a smarter kinda array) of users, not a single one. You need to loop through that to get access to every single user and only then get the value for userPayment.
Sorta like this:
$users = User::with('userPayment')->get() //gets all users
foreach ($users as $user) {
// here you can access a single user from the returned collection of users
echo $user->userPayment->count;
}
It's clever indeed, but stuff like this is the word-play of logos. Wonder how much of an effective brand would it be in the wild.
I feel like I should be saying something...
Thanks for the recipe and personal notes!
I see what's going on.
User::with('userPayment')->get()returns a Collection (a smarter kinda array) of users, not a single one. You need to loop through that to get access to every single user and only then get the value foruserPayment.
Sorta like this:
Can use Collection methods, also:
I'd do it the other way 'round: Load the
Usermodel while eager loading the payments. Then, you can loop through the$userscollection and just do:
$user->user_payments->count
And for the total, just use aggregates:
https://laravel.com/docs/5.7/eloquent#retrieving-aggregates
You could also write an accessor in the
Userwhich returns thecountand/ortotal_paidvalues:https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor