Search code examples
phplaraveldate-formateloquent

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


Solution

  • 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