Reputation: 63
I'm trying to access the User
model but its returning empty?
$topOnlineTime = UserStats::with('user')->orderBy('OnlineTime', 'DESC')->limit(10)->get();
In view:
@foreach ($topOnlineTime as $user)
{{ number_format($user->username) }}
@endforeach
username
belongs to the user model
class UserStats extends Authenticatable
{
protected $table = 'habbo_user_stats';
public $timestamps = false;
protected $guarded = ['id'];
public function user()
{
return $this->hasMany(User::class, 'id');
}
}
Here is the user model
class User extends Authenticatable
{
protected $table = 'habbo_users';
public $timestamps = true;
protected $guarded = ['id'];
public function userStats() {
return $this->belongsTo(UserStats::class, 'id');
}
}
Upvotes: 1
Views: 44
Reputation: 6808
Check my answer on Laravel: Issue with relationship? as I think the result for your loop is returning null because your migrations and relations are not set correctly.
Below is the answer for that question from me. I think after fixing that @Alexy Mezenin's answer above( https://stackoverflow.com/a/49082019/1409707) will work.
Here are things I noticed about your code
To confirm we would need to look into the database structure and migrations.
If a userstat have many users and a user belongs to 1 userstat.
the migrations will be
users table will have a user_stat_id and userstats table wont have a user_id
the code will look like this.
UserStatus.php
class UserStats extends Model
{
protected $table = 'habbo_user_stats';
public $timestamps = false;
protected $guarded = ['id'];
public function users()
{
return $this->hasMany(User::class, 'user_stat_id');
}
}
User.php
class User extends Authenticatable
{
protected $table = 'habbo_users';
public $timestamps = true;
protected $guarded = ['id'];
public function stat() {
return $this->belongsTo(UserStats::class, 'user_stat_id');
}
}
Upvotes: 1
Reputation: 163898
Since UserStats
has many User
records, you need to iterate over users too:
@foreach ($topOnlineTime as $userStats)
@foreach ($userStats->user as $user)
{{ $user->username }}
@endforeach
@endforeach
Upvotes: 2