Anansewaa
accessors and mutators

How to change date format with accessors and mutators in laravel 5.2

Dealing with a date can be stressful at times. Date field in MySQL Database has a default format of YYYY-MM-DD. And bootstrap datepicker gives a date format of in DD/MM/YYYY. How do I handle it properly in Laravel?

Well, my research gave me a couple of ways to do this, as usual in programming. We will be converting to a proper format before inserting into the database whenever you need to do an insertion. 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 the database (mutators) and after extracting it (accessor).

So, for instance, we have model Employee and a field date_of_birth – we can add two additional functions:  getDateOfBirthValue() and setDateOfBirthValue().

Their purpose is opposite to each other, and the syntax is different. Let’s give it a try:

 

The explanation of the code above :

  • Function names consist of three parts: get/set verb, the name of the field where underscores _ in the name of the field is changed to camelcase, thus from date_of_birth to DateOfBirth and word “value”.
  • Function getDateOfBirthValue() will be triggered every time you try to retrieve data from the database, like Employee::all() – you will receive date_of_birth column in DD/MM/Y format and you don’t have to do anything extra in the controller view
  • Function setStartDateValue() is triggered before the data is saved to the employees table. Something like Employee::create() Or $employee->save(). The function is expecting your value to be passed as DD/MM/Y (from the datepicker or text field) and then convert it into a YYYY-MM-DD format before saving to the database
  • Please take note of the difference in the 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() do not work properly with M/d/Y format. So in the second function, we have to treat the date as a string, split it and recompile in a different format.

Thanks for reading this article feel free to use it to your own advantage

Clemence Ayekple

Let's grab a cup of coffee and talk about programming

Add comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Most discussed

%d bloggers like this: