12

How to change date-format in laravel from "2016-03-12" to "12-Mar-2016"

$results = DB::table('customers as cust')
        ->where('cust.id',$id)
        ->select("cust.*","cust.cust_dob as dob")
        ->first();

Should I use laravel raw query.

I tried this,

 ->select("cust.*","DATE_FORMAT(cust.cust_dob, '%d-%M-%Y') as formatted_dob")

Any guide on this please.

GRESPL Nagpur
  • 2,048
  • 3
  • 20
  • 40

5 Answers5

34

Try to use this:

$results = DB::table('customers as cust')
             ->where('cust.id',$id)
             ->select(DB::raw('DATE_FORMAT(cust.cust_dob, "%d-%b-%Y") as formatted_dob'))
             ->first();
Rohit Suthar
  • 3,528
  • 1
  • 42
  • 48
cronLancer
  • 349
  • 2
  • 3
9

As there is no way except using raw query, I am using like this. It worked for me.

->select("cust.*", DB::raw("DATE_FORMAT(cust.cust_dob, '%d-%b-%Y') as formatted_dob"))
GRESPL Nagpur
  • 2,048
  • 3
  • 20
  • 40
9

Laravel use Carbon for datetime so you can write it like following code:

$results = DB::table('customers as cust')
            ->where('cust.id',$id)
            ->select("cust.*","cust.cust_dob as dob")
            ->first();
echo $results->dob->format('d-m-Y');
Zamrony P. Juhara
  • 5,222
  • 2
  • 24
  • 40
0

You can always use Carbon's ->format('m/d/Y'); to change format.

Or you can just use selectRaw to build your queries.

Also, you can try to use date mutators by settting $dateFormat to date format you want to use: https://laravel.com/docs/5.1/eloquent-mutators#date-mutators

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

Laravel gives a opportunity to define accessors/mutators. Which you can use in this case rather than to do it via Queries.

i would add method in Customer model class

public function getCustDobAttribute($value) {
    return //Format the value Which represent the value in database;
}

Example: Imagine you want retrieve customer name, You want get it as First charterer capital and the rest small.

public function getFirstNameAttribute($value)
{
    return ucfirst($value);
}

Reference:

https://laravel.com/docs/5.1/eloquent-mutators#accessors-and-mutators

devnull
  • 1,848
  • 2
  • 15
  • 23