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();
Share:
11,453

Related videos on Youtube

Lukho Mdingi
Author by

Lukho Mdingi

I write code.

Updated on September 15, 2022

Comments

  • Lukho Mdingi
    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
      sumit over 5 years
      One post can have many friend or just one?
    • Lukho Mdingi
      Lukho Mdingi over 5 years
      $post->user and $post->friend are two different results. But I had already created a function that checks if ($post->friend->id == ?), I was trying to avoid duplicating it with: if ($post->user->id == ?)
    • WhyAyala
      WhyAyala over 5 years
      I'm not sure I understand, you already have a relationship definition for friend and it's result is different from user?
  • Lukho Mdingi
    Lukho Mdingi over 5 years
    $post->user and $post->friend are two different results. But I had already created a function that checks if ($post->friend->id == ?), I was trying to avoid duplicating it like: if ($post->user->id == ?)
  • WhyAyala
    WhyAyala about 5 years
    Some one upvoted my answer, for some reason. I forgot to follow up on this. Is there any need for an update @LukhoMdingi ?
  • Lukho Mdingi
    Lukho Mdingi about 5 years
    I never actually found a solution to this. I had to work around it.