Laravel Eloquent using an alias with the with() function
11,453
Short answer is no, but you can define your relationship with the alias you want to use and eager load that.
class Post extends Model
public function user(){
return $this->belongsTo(User::class);
}
public function friend(){
return $this->user()
}
}
$posts = Post::where(/*condition*/)->with('friend')->get();
Related videos on Youtube
Comments
-
Lukho Mdingi about 1 year
Good day. Is it possible to use an alias name when using the with() function in laravel? For an example:
$posts = Post::where(/*condition*/)->with('user as friend')->get();
-
sumit over 5 yearsOne post can have many friend or just one?
-
Lukho Mdingi over 5 years
$post->user
and$post->friend
are two different results. But I had already created a function that checksif ($post->friend->id == ?)
, I was trying to avoid duplicating it with:if ($post->user->id == ?)
-
WhyAyala over 5 yearsI'm not sure I understand, you already have a relationship definition for
friend
and it's result is different fromuser
?
-
-
Lukho Mdingi over 5 years
$post->user
and$post->friend
are two different results. But I had already created a function that checksif ($post->friend->id == ?)
, I was trying to avoid duplicating it like:if ($post->user->id == ?)
-
WhyAyala about 5 yearsSome one upvoted my answer, for some reason. I forgot to follow up on this. Is there any need for an update @LukhoMdingi ?
-
Lukho Mdingi about 5 yearsI never actually found a solution to this. I had to work around it.