Urudin
Urudin

Reputation: 331

Manipulate request data using backpack 4.1

I'd like to change a data before saving I have a date where I don't need seconds only minutes, and I want the seconds to be 00 all the time. I tried Laravel's prepareForValidation() method in my request class, but it turned out it does not affect value stored in database. I also tried backpack's modifyField() but I couldn't find a way to modify value before store or update.

What's the best way to perform this? Using Laravel7 and Backpack 4.1

Upvotes: 1

Views: 619

Answers (1)

Dave Mills
Dave Mills

Reputation: 56

I don't know if there's a specific backpack way of doing it, but you can use a mutator on your model to modify the value before it gets saved to the database.

In your case, if your fieldname is "date_time" you could do something like:

class MyModel extends Model {

  setDateTimeAttribute ($value) {

    $value = Carbon::parse($value)->second(0);

    $this->attributes['date_time'] = $value;  
  }
}

This has the benefit that the mutation will occur every time your date_time attribute is updated - whether you update it through your Backpack Crud or from some other method.

References:

Upvotes: 4

Related Questions