danyal14's avatar

Eloquent Mutators and Accessors in Lumen

Hi Guys,

I am trying to update a field, using "Mutators" change to database is not happening. Any Idea

In controller

 $breakingNews = BreakingNews::findOrFail($id);
 $breakingNews->setAttribute('expired_at', Carbon::today()->format('Y-m-d H:i:s'));
 $breakingNews->save();

/**
     * @param null $value
     */
    public function setExpiredAtAttribute($value)
    {
        if (!$value) {
            $this->attributes['expired_at'] = Carbon::today()->format('Y-m-d H:i:s');
        } else {
            $this->attributes['expired_at'] = $value;
        }
    }

I also followed the link https://code.tutsplus.com/tutorials/eloquent-mutators-and-accessors-in-laravel--cms-30312

0 likes
4 replies
Vilfago's avatar

It should be

 $breakingNews = BreakingNews::findOrFail($id);
 $breakingNews->expired_at = Carbon::today()->format('Y-m-d H:i:s'));
 $breakingNews->save();

But in your model, you will always have a $value, so if (!$value) { is not relevant.

You better have to choose a default value in your database as CURRENT_TIMESTAMP.

This doc is far better than yours : https://laravel.com/docs/5.6/eloquent-mutators#defining-a-mutator :)

And last but not least, I don't know if Mutators are available in Lumen.

danyal14's avatar

@VILFAGO - It shouldn't be necessarily like this.

            $breakingNews = BreakingNews::findOrFail($id);
            $breakingNews->setAttribute('expired_at', Carbon::now());
            $breakingNews->save();

Worked for me now with same code but using now()

Vilfago's avatar

Yeah... but did you try to set another date ?

I think it will not work.

danyal14's avatar

@VILFAGO - I try it with other date, but the what is the benefit of ->setAttribute?

Please or to participate in this conversation.