1

I want to change the date format from 1990-01-30 to 30/01/1990 straight from my migration. I get the following error when I try to migrate with seeding from factory.

Invalid datetime format: 1292 Incorrect date value: '30/01/1990' for column 'dob' at row 1

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('fname');
        $table->string('lname');
        $table->string('phone')->unique();
        $table->date('dob')->format('d/m/Y');
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
justice
  • 75
  • 1
  • 2
  • 11
  • Formatting a date is usually done at the application layer - definitely not in the DB. I am pretty sure there is no way to specify a format for a date col in MySQL, at least. Neither is there any mention of `format()` modifier in [the Laravel migration docs](https://laravel.com/docs/6.x/migrations#columns). My guess is your `format()` is simply being ignored, and a normal `date` col is being created. Best solution would be to [`cast` your date to the format you want](https://laravel.com/docs/6.x/eloquent-mutators#date-casting). – Don't Panic Jan 21 '20 at 08:43

2 Answers2

2

Declare in model:

class ModelName extends Model
{      

 protected $casts = [
    'created_at' => 'datetime:d/m/Y', // Change your format
    'updated_at' => 'datetime:d/m/Y',
];
}
Anil Stha
  • 515
  • 7
  • 12
1

You can't do that within a migration. You will need to use Carbon and format the date in your Model instead.

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
  • i used this `'dob' => Carbon::createFromFormat('d/m/Y', '01/01/1990')->format('d/m/Y'),` in my factory. This is able to change the date format in the factory but the structure of the database still remains this format (Y-m-d), hence giving this error `Invalid datetime format: 1292 Incorrect date value: '30/01/1990' for column 'dob' at row 1` – justice Jan 16 '20 at 17:16