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?
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With