mercredi 21 octobre 2015

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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire