On Laravel 5.8, since I wanted to use it with eager loading I used this package:
https://github.com/staudenmeir/eloquent-has-many-deep
This was my scenario
A user can be tagged on many photo and a photo can have many users tagged on. I wanted to have a relationship to get the latest photo the user has been tagged on.
I think my scenario can also be applied to any many-to-many relationship
I did the pivot model UserPhoto
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class UserPhoto extends Pivot
{
public function user()
{
return $this->belongsTo(User::class);
}
public function photo()
{
return $this->belongsTo(Photo::class);
}
}
And then on my User model using staudenmeir's package:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Staudenmeir\EloquentHasManyDeep\HasRelationships;
class User extends Model
{
use HasRelationships;
public function photos()
{
return $this->belongsToMany(Photo::class);
}
public function latestPhoto()
{
return $this->hasOneDeep(Photo::class, [UserPhoto::class])
->latest();
}
}
Then I can easily do something like this:
User::with('latestPhoto')->get()
and $user->latestPhoto
Edit:
In an another question, someone asked the same without using a package.
I also provided an answer that will do the same result.
But after digging deeper, from both answers, you may avoid the n+1 query, you will still hydrate all the photos from your requested users. I don't think it's possible to avoid one or the other approach. The cache could be an answer though.