Nitish Kumar
Nitish Kumar

Reputation: 6276

How to get latest eloquent relationship by column name in Laravel

I am building a small application on Laravel 5.6 where I am having two models Project and Status. In this I am having a relation as such:

In Project Model I am having:

public function statusUpdate()
{
    return $this->hasMany('App\Status','project_id','id');

}

and to retrieve latest status I have:

public function latestStatus()
{
    return $this->hasOne('App\Status','project_id','id')->latest();
}

In status I have columns: date, status, sub_status, comments.

I want to retrieve Status where I am having latest status by date mentioned in the column

I tried doing this in my model:

public function latestStatus()
{
    return $this->hasOne('App\Status','project_id','id')->latest('date');
}

But this thing is not working out, help me out in this. Thanks

edit

I am using this relation in eager loading something like this:

Project::when( $request->name , function( $q) use( $request ) {
    $q->where('name', 'like', '%' . $request->name .'%');
})->with('latestStatus')
    ->orderBy($request->sort_by_col, $request->order_by)
    ->paginate(30);

Upvotes: 0

Views: 4069

Answers (3)

Dimitri Mostrey
Dimitri Mostrey

Reputation: 2340

You got your models wrong. This is what should be in the Project model

public function statuses() //plural because a project has many statuses
{
   return $this->hasMany('App\Status','id','project_id');
}

If you want the latest status, call this in your controller:

Project::where('name', 'like', "%{$request->name}%")->with('statuses', function($q) {
  return $q->orderBy('date', $request->order_by);
})->paginate(30);

If you want the latest project where the status has changed, first the Status model:

public function project() 
{
   return $this->hasOne('App\Project','project_id','id');
}

And in your controller:

$project = Status::latest()->first()->project;

Upvotes: 0

Saurabh
Saurabh

Reputation: 469

Add first to the end of the query.

public function latestStatus()
{
    return $this->hasOne('App\Status','project_id','id')->latest()->first();
}

This is how it works

  1. The statusUpdate method builds the query and does the setup for has many relationship
  2. The latest method adds the order by clause
  3. The first methods adds the limit 1 clause, then executes the query and returns the first result

Upvotes: -1

Rutvij Kothari
Rutvij Kothari

Reputation: 1285

You can use orderBy in the relationship.

public function latestStatus()
{
    return $this->hasOne('App\Status','project_id','id')->orderBy('date', 'desc');
}

Try it out.

Upvotes: 3

Related Questions