Formatting date with Laravel

Asked

Viewed 7,452 times

3

I’m unable to change the date format using the laravel 5.4

My model is like this:

class Feriado extends Model{

    protected $fillable = ['id', 'data', 'descricao', 'created_at', 'updated_at' ];
    protected $dates = ['data'=> 'm-d-Y'];
    protected $primaryKey = 'id';
    protected $table = 'feriados';

}

The controller that returns the data is like this:

public function index(){
        $feriados= Feriado::all();

        return response()->json(['error'=> false, 'mensagem'=> null, 'data'=> $feriados]);
    }

And the return is coming like this:

{  
   "error":false,
   "mensagem":null,
   "data":[  
      {  
         "id":1,
         "data":"2018-01-01 00:00:00",
         "descricao":"Confraterniza\u00e7\u00e3o Universal",
         "created_at":null,
         "updated_at":null
      },
      {  
         "id":2,
         "data":"2018-03-30 00:00:00",
         "descricao":"Sexta-feira Santa",
         "created_at":null,
         "updated_at":null
      },
      {  
         "id":3,
         "data":"2018-04-21 00:00:00",
         "descricao":"Tiradentes",
         "created_at":null,
         "updated_at":null
      },
      {  
         "id":4,
         "data":"2018-05-01 00:00:00",
         "descricao":"Dia do Trabalhador",
         "created_at":null,
         "updated_at":null
      },
      {  
         "id":5,
         "data":"2018-05-31 00:00:00",
         "descricao":"Corpus Christi",
         "created_at":null,
         "updated_at":null
      },
      {  
         "id":6,
         "data":"2018-09-07 00:00:00",
         "descricao":"Independ\u00eancia do Brasil",
         "created_at":null,
         "updated_at":null
      },
      {  
         "id":7,
         "data":"2018-10-12 00:00:00",
         "descricao":"Padroeira do Brasil",
         "created_at":null,
         "updated_at":null
      },
      {  
         "id":8,
         "data":"2018-02-11 00:00:00",
         "descricao":"Finados",
         "created_at":null,
         "updated_at":null
      },
      {  
         "id":9,
         "data":"2018-11-15 00:00:00",
         "descricao":"Proclama\u00e7\u00e3o da Rep\u00fablica",
         "created_at":null,
         "updated_at":null
      },
      {  
         "id":10,
         "data":"2018-12-25 00:00:00",
         "descricao":"Natal",
         "created_at":null,
         "updated_at":null
      }
   ]
}

The date is coming in format 2018-12-25 00:00:00 and in the model I am setting another format protected $dates = ['data'=> 'm-d-Y'];

I wonder where I’m going wrong?

To display the data on the screen I am using Angularjs, and even using a filter {{(feriado.data| date: 'dd-MM-yyyy')}} does not display in the correct form.

  • https://laravel.com/docs/5.5/eloquent-serialization#appending-values-to-json read this .

  • I was able to define in the model no :( even after everything again...

  • I made a reply using your model try to understand and reflect in your code the example ...

4 answers

2


Don’t change anything in yours model in the standard question, only make a new field that will be shown from the results of the same, if you want a date in the specific pattern, create a method that will be appended to the values returned from a query, both array and json, one minimal example:

Configure your Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Feriado extends Model
{
    protected $primaryKey = 'id';
    protected $table = 'feriado';
    protected $fillable = ['id', 'data', 'descricao'];
    protected $dates = ['created_at','updated_at'];

    //data formatada m-d-Y
    protected $appends = ['data2'];
    public function getData2Attribute()
    {
        return date('m-d-Y', strtotime($this->attributes['data']));
    }

}

that configuration $appends will only serve to show data, has no relation to the fields that relate to the table, but, use them to show certain types of values and formats. The method getData2Attribute() has the responsibility to make this conversion and show the formatted date (which can be of any format, depends on the established rule), and everything is independent of the standard of the table in the bank is this useful to keep the operations without conversion problem, this field that was attached is only used when to display information in the methods, example:

>>> App\Models\Feriado::all()->toArray();    
=> [                                         
     [                                       
       "id" => 1,                            
       "data" => "2016-10-09",               
       "descricao" => "Festival",            
       "created_at" => "2017-10-27 00:00:00",
       "updated_at" => null,                 
       "data2" => "10-09-2016",              
     ],                                      
     [                                       
       "id" => 2,                            
       "data" => "2016-11-11",               
       "descricao" => "Carnaval",            
       "created_at" => "2017-10-27 00:00:00",
       "updated_at" => null,                 
       "data2" => "11-11-2016",              
     ],                                      
   ]                                         
>>> 

in this example the attached field data2 is in the expected format. There is confusion in the Mutators for the purpose of changing the recovery characteristic of the Model, which in many cases breaks the logic and gives many problems if done wrong. It is widely used in Date fields or DateTime (but, any field can be employable), but, need to understand that at all times you must use the class conventions and format the data and to update your information must be an instance of the class DateTime, quite different from the first example which is the best solution for your case.

References:

1

1

the date format of your bank this Y-m-d, which is the default, use function $holidays->data->format(’d/m/Y') in your view.

0

Try David Santos' solution, it should work, but an alternative if not certain, would be to make the change in hand, is a gambit but it works:

public function index(){
    $feriados= Feriado::all();
    foreach($feriados as $feriado){
        $feriado->data = date("d-m-Y", strtotime($feriado->data));
    }
    return response()->json(['error'=> false, 'mensagem'=> null, 'data'=> $feriados]);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.