Carol.Kar
Carol.Kar

Reputation: 5215

created_at/updated_at is null when seading file

I am using laravel and I have created the following seeder:

    public function run()
    {
        $faker = Faker\Factory::create();
        $limit = 20;

        for ($i = 0; $i < $limit; $i++) {
            DB::table('data_sources')->insert([
                'name' => $faker->name(),
                'description' => $faker->sentence(),
            ]);
        }
    }

My migration file looks like the following:

    public function up()
    {
        Schema::create('data_sources', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->nullable();
            $table->string('description')->nullable();
            $table->unsignedBigInteger('google_sheets_id')->nullable();
            $table->foreign('google_sheets_id')->references('id')->on('google_sheets')->onDelete('cascade');
            $table->timestamps();
        });
    }

When running the seeder only name and description gets updated.

Any suggestions why timestamps() do not get updated?

Appreciate your replies!

Upvotes: 0

Views: 537

Answers (3)

Kay
Kay

Reputation: 508

Add this to your seeder

'created_at' => Carbon::now()->format('Y-m-d H:i:s');
'updated_at' => Carbon::now()->format('Y-m-d H:i:s');

Don't forget to import Carbon class

Upvotes: 1

The created_at and updated_at attributes will be set automatically if you use Eloquent model.

But you are using Raw SQL Queries. In this case, you need to insert the data manually as following.

On top of the class

use \Illuminate\Support\Carbon;

And modify your run method with created_at, updated_at

public function run()
{
    $faker = Faker\Factory::create();
    $limit = 20;

    for ($i = 0; $i < $limit; $i++) {
        DB::table('data_sources')->insert([
            'name' => $faker->name(),
            'description' => $faker->sentence(),
            'created_at' => Carbon::now()->toDateTimeString(),
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);
    }
}

Upvotes: 1

Hafez Divandari
Hafez Divandari

Reputation: 9069

The created_at and updated_at attributes will be set automatically if you use Eloquent model. if you don't have a model for your data_sources table, you can create one:

php artisan make:model DataSource

Then use it to insert a new record:

$dataSource = new DataSource;
$dataSource->name = $faker->name();
$dataSource->description = $faker->sentence();
$dataSource->save();

Or using create method:

App\DataSource::create([
    'name' => $faker->name(),
    'description' => $faker->sentence(),
]);

Note: the create method protects the model against mass-assignment by default, so don't forget to define $fillable property on the model:

protected $fillable = ['name', 'description'];

Upvotes: 2

Related Questions