John Davidson

php - Laravel eloquent call optional relationship in query

0 comments
Message:


I am trying to get a query with Laravel eloquent. I have a table posts which has a morph relationship column author. This author column can refer to a users table or admins table. So this is the way I am getting the author of each posts:


    $query = Post::with(['author']);

Now, there's another table I want to include if the author is a user, which is address. The problem is, there's no address relationship in admin table.

So, when I try to do this,


    $query = Post::with([
'author' => function ($q) {
$q->with('address');
}
]);

It throws me Illuminate\Database\Eloquent\RelationNotFoundException exception as the relation address is not defined for admin.

How do I solve this problem? I want fetch all the posts with author and include address in the authors that has an address



My Answer:
> function($query) {
> $query->with('address');
> }
> ])->get();

Rate this post

5 of 5 based on 2796 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us