Try creating an pivot model for the package_session table and then apply the oldest("start_date") method https://laravel.com/docs/9.x/eloquent-relationships#defining-custom-intermediate-table-models
How to order by the latest many to many relation
I am currently working on a application that offers courses - in this case it is called a sessions.
Session come packaged into sessions that can occur on one or more days There is a many to many relationship between a package and a session.
class Package extends Model
{
public function sessions()
{
return $this->belongsToMany(Session::class, 'package_session', 'package_id', 'session_id');
}
class Session extends Model
{
public function packages()
{
return $this->belongsToMany(Package::class, 'package_session', 'session_id', 'package_id');
}
The pivot table is package_session On the offerings page the pages are listed along with the related sessions. I am trying to sort the packages by order of the soonest sessions.start_date per package.
This almost gets me there but it returns the relation as a collection.
public function latestSession()
{
return $this->belongsToMany(Session::class, 'package_session')
->oldest('start_date');
}
And this
return $this->belongsToMany(Session::class, 'package_session')
->oldest('start_date')->first();
throws an error: Call to undefined method App\Session::getRelated()
Is there a way to do this using eloquent?
Please or to participate in this conversation.