How to change date format in laravel Query Builder from "2016-03-12" to "12-Mar-2016" [duplicate]
Asked Answered
E

5

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.

Ellaelladine answered 10/3, 2016 at 6:58 Comment(1)
you can use raw query builder .. It will look like normal queryHollowell
T
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');
Tchao answered 10/3, 2016 at 7:18 Comment(0)
G
36

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();
Greater answered 10/3, 2016 at 8:3 Comment(1)
runs the date_format on every row, if number increases, performance will go downKnownothing
E
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"))
Ellaelladine answered 10/3, 2016 at 7:15 Comment(0)
T
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');
Tchao answered 10/3, 2016 at 7:18 Comment(0)
I
1

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

Isidora answered 10/3, 2016 at 7:31 Comment(0)
R
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

Renell answered 10/3, 2016 at 7:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.