How to use Select with MySQL DATE_FORMAT() in Laravel?

By Hardik Savani | March 16, 2017 | | 2569 Viewer | Category : Laravel MySql


Share this post:

We sometimes require to use MySQL pre-define function like sum(), date_format(), year(), month(), group_concat() etc. But laravel query builder not provide to directly use with select statement. However, we can use all the pre-define function of Mysql using DB::raw().

So, In this post i am going to share with you how to use date_format() in Laravel 5 Query Builder. date_formt() help us to change date format. We may sometimes require to change date format using mysql date_format().

In this example i have simple "users" table and there are some dummy users with created_at row with current timestamps. We will change format "%d-%b-%Y" from timestamps. So i added single route for testing demo how it is work. So let's use bellow route with query:

Example:

Route::get('date-format', function () {


$users = DB::table("users")

->select("users.name", DB::raw("DATE_FORMAT(created_at, '%d-%b-%Y') as formatted_date"))

->get();


dd($users);

});

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => stdClass Object

(

[name] => Hardik Savani

[formatted_date] => 10-Mar-2017

)

[1] => stdClass Object

(

[name] => Harsukh Makawana

[formatted_date] => 04-Jan-2016

)

[2] => stdClass Object

(

[name] => Vimal Kashiyani

[formatted_date] => 07-Jan-2016

)

[3] => stdClass Object

(

[name] => Harshad Pathak

[formatted_date] => 07-Jan-2016

)

)

)

I hope it can help you...



We are Recommending you: