5

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?

kayex
  • 119
  • 5

1 Answers1

1

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
});
whoan
  • 8,143
  • 4
  • 39
  • 48