skip to Main Content

I have a problem to eagerload 2 relation in 1 table in laravel 9. i have table called photos have relation with users and photo_categories. so what i want to achieve is to load user and categories in same time.also im already declare the relation at the model.
what i already try is like code bellow

$photos = Photo::with('user','photoCategory')->where('id',$request->id)->first(); //at show method

$photos = new PhotoCollection(Photo::with('user','photoCategories')->OrderByDesc('id')->paginate(10));//at index method

my relation at Photo Model

public function user(){
 return $this->BelongsTo(User::class);
}
public function photoCategory(){
 return $this->HasMany(FotoCategory::class);
}

my relation at user model

public function photo(){
 return $this->HasMany(PhotoCategory::class);
}

my relation at user photoCategory model

public function photo(){
 return $this->BelongsTo(Photo::class);
}

please help me to figure out the problems
thankyou in advance

2

Answers


  1. It looks like you have issues with your Photo model. The photoCategory method should be BelongsTo relationship:

    public function photoCategory()
    {
        return $this->belongsTo(PhotoCategory::class);
    }

    In user model :

    public function photos()
    {
        return $this->hasMany(Photo::class);
    }

    Here is final output relationship data :

    $photos = Photo::with('user', 'photoCategory')->where('id', $request->id)->first();
    
    $photos = new PhotoCollection(Photo::with('user', 'photoCategory')->orderByDesc('id')->paginate(10));

    Hope this will help you.

    Login or Signup to reply.
  2. It looks like there is a typo in your code where you are calling photoCategories instead of photoCategory in the with method when eager loading the photoCategory relation.

    Try updating your code like this:

    $photos = Photo::with('user', 'photoCategory')->where('id', $request->id)->first(); //at show method
    
    $photos = new PhotoCollection(Photo::with('user', 'photoCategory')->orderByDesc('id')->paginate(10)); //at index method
    

    Also, make sure that your PhotoCategory model has a belongsTo relationship to Photo model, like this:

    public function photo(){
        return $this->belongsTo(Photo::class);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search