I started using laravel a couple of days ago. I have a lot of experience in other frameworks but i'm straggling a bit with the Eloquent ORM and the relationships.
Say that a user has another table holding its stats. I create that relationship. Now the user also has many posts so i declare that too.
class User extends Authenticatable
{
public function userDynamic()
{
return $this->hasOne('App\UserDynamic', 'user_id', 'id');
}
public function posts()
{
return $this->hasMany('App\Post');
}
}
At the other models now we have:
class UserDynamic extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
And:
class Post extends Model
{
public function user()
{
$this->belongsTo('App\User','user_id','id');
}
}
I think i have it right this far. Problem comes when trying to retrieve those. For one user i'm fine cause i cant
$user ( get user from auth token)
$user->stats = $user->userDynamic()->first();
$user->posts = $user->posts()->paginate($this->profilePagination);
Which is good, i get the user with an attribute stats containing all info and the posts in an attribute posts.
How ever if i'm trying to get all users like below
$users = User::with('userDynamic')->active()->notPrivate();
return $users->paginate($this->followersPagination);
All the users are returned like so
{
"id": 26,
"name": "LL",
"url": "",
"personal_quote": "",
"private": "0",
"active": "1",
"user_dynamic": {
"user_id": 26,
"following_count": 7,
"followers_count": 0,
"posts_count": 0,
"likes_count": 0
}
How can i change the attribute name that they are assigned ? Instead of user_dynamic to say like stats.
If you're intent on keeping the name of your userDynamic
relation then you can simply add an alias for that relation:
public function stats()
{
return $this->userDynamic();
}