Reputation: 2000
I have a pivot relationship as below:
public function users()
{
return $this->belongsToMany(User::class,'pet_owners','pet_id','owner_id');
}
now in my controller i want to get the latest item of this pivot table which is sorted by created_at field . here is how i get it now :
$pets = Pet::with('users')->get();
return new PetResource($pets);
here I want to show all pets with the latest user entered for that pet in the pivot table
Upvotes: 0
Views: 61
Reputation: 11424
Limiting eager loads is unfortunately not easily done with Eloquent. There are many issues related to this on the Github repo. You can read this thread for an overview.
One of Laravel's contributors released a package staudenmeir/eloquent-eager-limit to make it easier to limit eager loads. You can install it with:
composer require staudenmeir/eloquent-eager-limit:"^1.0"
You need to add the \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
trait to both your Pet
and User
models. Then you'll be able to use the limit
method on a query inside a with
method on your model:
$pets = Pet::with(['users' => function ($query) {
return $query->latest()->limit(1);
}])->get();
Upvotes: 1
Reputation: 304
You can use this way,
$pets = Pet::whereHas('users', function($q){
$q->orderBy('id', 'DESC');
})->get();
return new PetResource($pets);
// return latest record of pivot table
Upvotes: 2