Reshma
Reshma

Reputation: 199

Date format Query in Laravel

My query for fetching a data from database is,

select mailboxtoolno,DATE_FORMAT(maileventdate,'%d %b %Y') as 
date,DATE_FORMAT(maileventdate,'%H:%i:%s') as time,mailtype from 
domiciliation_mailbox where reg_id =".$regid." order by id DESC

How can i change it to laravel eloquent model,

I have been trying to change it like,

 $timeline= mailbox::select('mailboxtoolno','DATE_FORMAT(maileventdate,"%d %b %Y") as date','DATE_FORMAT(maileventdate,"%H:%i:%s") as time','mailtype')
->where('reg_id', '=',$reg_id )
->paginate(10);

But got an error like,

Unknown column 'DATE_FORMAT(maileventdate,"%d %b %Y")' in 'field list'

How can i get the correct value in date format in laravel

Upvotes: 2

Views: 13883

Answers (2)

aaron0207
aaron0207

Reputation: 2333

Laravel doesn't support complex select expressions, so you have to use Raw Expressions. Try in this way:

    $timeline= mailbox::select('mailboxtoolno',DB::raw('DATE_FORMAT(maileventdate,"%d %b %Y") as date'),DB::raw('DATE_FORMAT(maileventdate,"%H:%i:%s") as time'),'mailtype')
->where('reg_id',$reg_id )
->orderBy('id','DESC')
->paginate(10);

In order to use ->orderBy() in this query you would have to set strict modes manually to ommit order by validation. Do it in your database.php config database connection array parameters:

'strict'    => true,
        'modes'     => [
            'STRICT_TRANS_TABLES',
            'NO_ZERO_IN_DATE',
            'NO_ZERO_DATE',
            'ERROR_FOR_DIVISION_BY_ZERO',
            'NO_AUTO_CREATE_USER',
            'NO_ENGINE_SUBSTITUTION'
        ],

Or set strict => false (I won't do it)

Upvotes: 3

Dharma Saputra
Dharma Saputra

Reputation: 1674

Use raw statement instead. For example:

$user = User::select(DB::raw('count(*) as user_count, status'))->where('status', '=', 'active');

By the way actually, Laravel has mutator for field with DateTime type. So you can select it as normal and format it later. Example;

$user = User::find(2);
$date = $user->created_at->format('d M Y'); // you can display it with any format you want with this way.

More information read the official documentation and this

Upvotes: 2

Related Questions