Laravel 5.2 Eloquent - Accessor through scope

I have a model in which I need to check values ​​and return unhealthy status. I created an Accessor that works and returns true or false as expected.

$task->unhealthy()

Access 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;
    }

Now I have a requirement to get a collection of all the "unhealthy" tasks.

Question . Can I use my Accessor with scope? What would be the right approach?

+4
source share
1 answer

You can use the collectionfilter() method to filter only unhealthy tasks when you have a collection with all tasks:

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

Source: https://habr.com/ru/post/1651229/


All Articles