Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent using an alias with the with() function

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();
like image 373
Lukho Mdingi Avatar asked Feb 27 '18 21:02

Lukho Mdingi


1 Answers

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();
like image 62
WhyAyala Avatar answered Nov 16 '22 08:11

WhyAyala