Skip to content

u/CastorNotPollux

In this archive from May 2015 to Oct 2018

0
posts
10
comments
0
media
39
score

Top comments

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 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; 
}

​

Can use Collection methods, also:

$users->each(function ($user) {
    echo $user->userPayment->count;
});

​

2 points

I'd do it the other way 'round: Load the User model while eager loading the payments. Then, you can loop through the $users collection 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 User which returns the count and/or total_paid values:

https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor

​

2 points

Subreddits

Keyboard shortcuts

Move and act

jork
Next / previous post or comment
Enteroro
Open the post
f
Open the media viewer
s
Save
h
Hide (the toast has Undo)
Tab
Right after an action: the toast's Undo
x
Collapse the comment
v
Next layout: cards, compact, grid

Go to

/
Search
gthenh
Home
gthena
All
gthens
Subreddits
gthenl
Library
?
This list
Esc
Close a menu or this list

In the viewer

←or→
Previous / next file
↑or↓
Previous / next post
korj
Previous / next post
Space
Play / pause
m
Mute
z
Zoom
s
Save
o
Open the post (on its own page: back to it)
Esc
Close

Keys do nothing while you type in a box.