Laravel 7 timestamp migration always return 0000-00-00 00:00:00 when importing a csv excel file

Viewed 265

I search all the related article but no solution. I was setting up a sitemap for Laravel when I realise the timestamp is not ok. So this is bad for SEO.

I always have those 0 in the created_at and updated_at field in the MySQL database.

I'm not sure if this is a Laravel, SQL or Excel question.

What I do:

  • migrate my table in laravel in my localhost $table->timestamps(); tried this also but no
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$timestamps = false;
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
  • I import the sql database in the server phpmyadmin from my localhost

  • And import the excel csv file in phpmyadmin with the data.

Maybe there's another way to properly do this?

1 Answers

If you are using maatwebsite/excel, and if you have created the timestamps through migration likewise, so the model will insert the timestamps automatically.

    $table->timestamps();

note: make sure that your table column created_at is not present in the fillable array of your model and you are not using the WithUpserts approach as mentioned in the documentation. see: https://docs.laravel-excel.com/3.1/imports/model.html

protected $fillable = [
         'users_id',
         'name',
         'created_at' //it should not be here
]

Another Approach with Carbon

you have to add the timestamps through the use of carbon.

First add the created_at in the fillable array of your model

 protected $fillable = [
          
             'name',
             'created_at' //must be present
    ]  

And then you have to use the carbon, go to your import folder and in your import file, bring the below changes which are marked with comments.

 <?php

namespace App\Imports;
use Carbon\Carbon; //add this line of code

use App\User;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;

class UsersImport implements ToModel
{
    /**
     * @param array $row
     *
     * @return User|null
     */
    public function model(array $row)
    {
        return new User([
           
           'created_at'=> now(),  //add this line of code
           'name'     => $row[0],
         

        ]);
    }
}

note: it is also applicable for the upserts, in upserts the maatwebsite is not able to add the timestamps it would be null, but with the above mentioned method you can store the timestamps, you can use the same method for updated_at.

Related