A Problem I Run Into – I Have A Date Field In MySQL Database, Which Has A Default Format Of YYYY-MM-DD, But Bootstrap Datepicker Gives A Date Format Of in DD/MM/YYYY. How Do I handle It Properly In Laravel?

Well, My Research Has Landed On Me a Couple Of Ways To Do This, As Usual In Programming. The Date Can Be Converted To A Proper String 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 DB (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:
 

Class Employee Extends Eloquent {
  private Function GetDateOfBirthValue() {
    return Date('d/m/Y', Strtotime($this->attributes['date_of_birth']));
  }
 
  private Function SetDateOfBirthValue($value) {
    $date_parts = Explode('/', $value);
    $this->attributes['date_of_birth'] = $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  where Underscores _ In The Name Of Field Is Changed To CamelCase, Thus From Date_of_birth To DateOfBirht And Word "Value".
  • Function GetStartDateValue() Will Be Triggered Every Time You Try To Retrieve data From The Database, Like Employee::all() – You Will Recieve Date_of_birth Column In D/m/Y Format And You Don’t Have To Do Anything Extra In Controller/view
  • Function SetStartDateValue() Will Be Triggered Before Saving Data To employees table – Something Like Employee::create() Or $employee->save(). Function Is Expecting Your Value To Be Passed As D/m/Y (from Datepicker Or Text Field) And Then Convert it Into A Proper YYYY-MM-DD Before Saving To DB
  • Please Take Note Of 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() 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. Thanks For Reading This Article -feel Free To Use It To Your Own Advantage