Change date format with Accessors and Mutators

Pretty common situation - you have a date field in the MySQL database, which has a default format of YYYY-MM-DD, but the users need to see/edit dates in MM/DD/YYYY. How do you handle it properly in Laravel? Well, as usual in programming, there are several ways. You can convert it to a proper string in the View files whenever you need, but the best place to handle it is actually Laravel Eloquent Model - with a help of Accessors and Mutators. These words basically mean functions which change the value of the field before saving to DB (mutators) and after extracting it (accessor). So, for example, we have model Event and a field start_date - we can add two additional functions: getStartDateValue() and setStartDateValue(). Their purpose is opposite to each other, and the syntax is pretty different. Let's take a look:
class Event extends Eloquent {

  private function getStartDateValue() {
    return date('m/d/Y', strtotime($this->attributes['start_date']));
  }

  private function setStartDateValue($value) {
    $date_parts = explode('/', $value);
    $this->attributes['start_date'] = $date_parts[2].'-'.$date_parts[0].'-'.$date_parts[1];
  }

}
Ok, there are several things to explain here. So one by one:
  • Function names consist of three parts: get/set verb, name of the field (note that underscore symbol _ is changed to CamelCase syntax - from start_date to StartDate) and word "Value"
  • Function getStartDateValue() will be triggered every time you take the data from the database, like Event::all() or something - you will recieve event_date column in m/d/Y format and you don't have to do anything extra in controller/view
  • Function setStartDateValue() will be triggered before saving data to events table - something like Event::create() or $event->save(). Function is expecting your value to be passed as m/d/Y (from datepicker or text field) and then transforms it into a proper YYYY-MM-DD before saving to DB
  • Please note a little different syntax of the functions - they are both working with $this->attributes array, but get function is taking the parameter by its index (so the function itself doesn't have any parameters), whereas set function has a parameter ($value) which is then transformed and assigned to $this->attributes array element.
  • PHP function strtotime() doesn't properly work with m/d/Y format, so in the second function we have to treat date as string, split it and recompile in a different format. Of course, there are other ways of doing it - feel free to use your own.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1056 lessons, total 44 h 09 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials