Question

I am using Laravel 4 and have two Models: Projects and Tasks. My Project.php is

class Project extends \Eloquent {
    protected $guarded = [];

    public function tasks()
    {
        return $this->hasMany('Task');
    }
}

And my Task.php is

class Task extends \Eloquent {
    protected $guarded = [];

    public function project()
    {
        return $this->belongsTo('Project');
    }
}

Pretty standard stuff till now.

Now I want to display the last 30 days. I am using nesbot/Carbon and I could do:

 $projects = Project::with('tasks')->where('created_at', '>', Carbon::now()->subDays(30))->get();

But this displays the projects from the last 30 days, but I want to display the tasks from the last 30 days. In the Laravel.io Chat I got the suggestion to use this:

 $projects = Project::with(['tasks' => function($query) { $query->where('created_at', '>', Carbon::now()->subDays(30)); }]);

But this isn't working either.

I would appreciate any advice on how to access the tasks from the last 30 days, while using model relations like I normally do in my Controller.

Love,

George :)

Was it helpful?

Solution

You need to use whereHas for the constraints to transfer over to the main Project query.

$constraint = function($query) {
    $query->where('created_at', '>', Carbon::now()->subDays(30));
};

Project::with(['tasks' => $constraint])
    ->whereHas(['tasks' => $constraint])
    ->get();

Note that you can drop the with() if you want to display all the projects' tasks.

This is somewhat inefficient and can be improved by using joins instead of whereHas, but should get you started.

OTHER TIPS

Actually the answer from the Laravel chat was right:

 $projects = Project::with(['tasks' => function($query) { $query->where('created_at', '>', Carbon::now()->subDays(30)); }]);

I just had forget the get()-Method. So the correct way had to be:

  $projects = Project::with(['tasks' => function($query) { $query->where('created_at', '>', Carbon::now()->subDays(30)); }])->get();

Regards to Connor_VG

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top