InvalidSyntax
InvalidSyntax

Reputation: 9495

Using mutator in Laravel to populate column

I have a column in my booking model which stores datetime as reservation_datetime, however in my forms I have split this into two separate fields (date & time html5 inputs).

I have created a setter mutator to store date derived from the two inputs, however nothing is saved into the reservation_datetime column when the record is inserted.

This is my mutator

public function setReservationDatetimeAttribute($value)
{
    return $this->attributes['reservation_datetime'] = $this->date . " " . $this->time;
}

I've noticed that if I put pseudo inputs into my $fillable array (reservation_datetime is already present) then I am able to set the mutator to the correct value but this causes other issues where the ORM is trying to save date and time columns which obviously doesn't exist causing an error on save.

Upvotes: 4

Views: 1047

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219920

Mutators are the wrong tool for this. Set reservation_datetime manually in your controller.

Mutators are meant to be used the other way around. For example if your form has a single field that you want to split in two, or to simply mutate the value of a single attribute.

Combining two attributes into one is simply not what mutators are about.

Upvotes: 3

Related Questions