Home > Software design >  How to change column from 'true' to 'false' with condition Laravel
How to change column from 'true' to 'false' with condition Laravel

Time:08-26

I have table with columns: -id -status -overdue_status -return_time

Default for -overdue_status column is 'false'. I want to make condition where if current time is smaller than 'return_time' column data, set it to 'true'. How to do that? Using mutators, accessors, events and listeners? How?

CodePudding user response:

You can define an accessor to calculate the overdue status by comparing to the current date and time :

    /**
     * Get the user's first name.
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function overdueStatus(): Attribute
    {
        return Attribute::make(
            get: fn () => {
                // return_time needs to be cast to a carbon date
                // by doing : protected $dates = ['return_time']; in the model
                return $this->return_time->lessThan(now());
            }
        );
    }

You will be able to access it using $item->overdue_status like before

  • Related