kayex
kayex

Reputation: 119

Laravel 5.2 Eloquent - Accessor through Scope

I have a model which I need to check values on and return back an unhealthy status. I have created an Accessor, which is working and returns true or false as expected.

$task->unhealthy()

Accessor code

    public function getUnhealthyAttribute(){

        //Is in Active status
        if ( $this->status_id == 1 ){
            return true;
        }

        //Has overdue items
        if ( $this->items()->overdue()->count() > 0 ) {
            return true;
        }

        return false;
    }

I now have a requirement to retrieve a collection of all "unhealthy" Tasks.

Question: Is it possible to leverage my Accessor with a scope? What would be the right approach?

Upvotes: 5

Views: 563

Answers (1)

whoan
whoan

Reputation: 8521

You can use the collection's filter() method to filter only the unhealthy tasks once you have a collection with all the tasks:

$unhealthy_tasks = $tasks->filter(function($task, $key) {
    return $task->unhealthy; // if returns true, will be in $unhealthy_tasks
});

Upvotes: 1

Related Questions