I want to get only the date of my BD record from the column 'created_at'

2

How can I format the 'created_at' ('Y-m-d') column in the laravel driver?

Since it shows me "2018-02-10 00:00:00"

I have this query

BD::select('created_at') 

shows me

"2018-02-10 00:00:00"
    
asked by alez 03.10.2018 в 00:55
source

2 answers

2

At the beginning of your Controller do the following

use DB;
  

The above code will help invoke the facade DB that helps   enable the use of the query builder so that you can build with it   queries with SQL code instead of using the ORM's own methods   Eloquent

Later within the class and the method you have designated for this query, perform the following query

sample code

This code is functional from an example that I did to you just adapt it to the name of your table

$data = DB::table('users')
        ->selectRaw('DATE(created_at) AS Fecha')
        ->get();

return $data;

Result obtained from the previous query

[
  {
   "Fecha": "2018-10-02"
  },
  {
   "Fecha": "2018-10-02"
  },
  {
   "Fecha": "2018-10-02"
  },
  {
   "Fecha": "2018-10-02"
  }
]

We make use of:

  • selectRaw() to be able to execute SQL functions that the ORM does not have by default
  • With the use of the function DATE() we pass the column created_at and optionally we assign an alias
  • answered by 03.10.2018 / 01:08
    source
    1

    The word "format" can give us problems when interpreting your question.

    In general, in a controller you should NOT change the format of the data you have in bbdd. You may have to operate with them, and the controller is the point to do it.

    Where you should change the format is in the PRESENTATION (that is, in the corresponding template). There you should format your data, to present them as you need.

    In case of laravel, you can use Carbon (as indicated by @ Fabio in your answer). In the controller, take the date

    $fecha = BD::select('created_at') 
    

    In your blade template you can put:

    {{ \Carbon\Carbon::parse($fecha)->format('d/m/Y')}}
    
        
    answered by 04.10.2018 в 00:10