Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 965
kayex Avatar asked Nov 09 '22 10:11

kayex


1 Answers

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
});
like image 183
whoan Avatar answered Nov 15 '22 10:11

whoan