mtpultz
mtpultz

Reputation: 18248

Laravel 5.1 Won't save date into database set as 00-00-00 00:00:00

I'm sending dates up using this Bootstrap datetimepicker with a format of MMM D, YYY created by MomentJS, which can't submit a different format than what is displayed to the user by default.

So on the server-side I added an mutator for the date in the model:

public function setStartDateAttribute($startDate) {
    //dd(Carbon::parse($startDate)->toDateTimeString());
    return Carbon::parse($startDate)->toDateTimeString();
}

Which when I dd the value looks like it should 2015-10-22 00:00:00, but it saves the date as 0000-00-00 00:00:00 or it just isn't setting the date at all, which I don't understand.

I don't want to change how the timestamps are formatted in the database so I didn't set $dateFormat and set 'start_date' in the $dates array of the Model. Thought an mutator seemed easier. The field is set to date() in the migration file, and I'm pretty sure I've done this before and it just worked. So I tried it in the my controller without the mutator and the same line works:

public function update(TournamentRequest $request, $tournamentId)
{
    // Update a tournament with all fillable data, and persist to database
    $tournament = Tournament::find($tournamentId)->fill($request->except('start_date'));
    $tournament->start_date = Carbon::parse($request->start_date)->toDateTimeString();
    $tournament->save();

    return Redirect::route('dashboard.tournaments.index');
}

Why does the same code work inside the controller without the mutator setup in the Model, but not work when using the mutator?

Upvotes: 1

Views: 1000

Answers (1)

Sandyandi N. dela Cruz
Sandyandi N. dela Cruz

Reputation: 1345

This is how you make a setter method for your attribute. Note: you don't return anything, you just assign a value to the attribute:

public function setStartDateAttribute($startDate) {
    $this->attributes['start_date'] = Carbon::parse($startDate)->toDateTimeString();
}

That's assuming you want to set a field named start_date in your table.

Upvotes: 1

Related Questions