Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent model not updating updated_at timestamp

I'm using Laravel 5.1. To make it simple, I have the following code

Migration:

Schema::create('sitemap_data', function (Blueprint $table) {
    // Primary and foreign keys
    $table->increments('id');
    $table->string('postUrl');
    // Database functions
    $table->timestamps();
});

And this is the code somewhere else I'm using

$sitemapData = SitemapData::firstOrNew([
                'postUrl' => $post
            ]);
$sitemapData->save();

Now, according to the Laravel documentation

Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value

The updated_at value should be updated in the table. However, this is not happening.

It get's only set on the first insert, but not on updating. When I do it manually, like this

$sitemapData = SitemapData::firstOrNew([
                    'postUrl' => $post
                ]);
$sitemapData->updated_at = Carbon::now();
$sitemapData->save();

it works. However, the docs say this should happend automatically, so what is wrong here?

I've searched some sites on stackoverflow for this question, but the ones I found where for Laravel 3 or 4.1, 4.2 etc.

How would I do that correctly?

like image 745
Musterknabe Avatar asked Jun 15 '15 12:06

Musterknabe


3 Answers

As mentioned in comments, if the model did not change the timestamps wont be updated. However if you need to update them, or want to check if everything is working fine use $model->touch() - more here

like image 64
Pawel Bieszczad Avatar answered Nov 17 '22 08:11

Pawel Bieszczad


It is possible actually:

$model->updated_at = Carbon::now();
$model->save(['timestamps' => FALSE]);

That will properly save the updated_at to now. If you're not sure if any of the model's columns have changed, but you do want to update the updated_at regardless - this is the way to go.

like image 6
Stan Smulders Avatar answered Nov 17 '22 08:11

Stan Smulders


Yeah what Musterknabe has done is correct but he should also check his model SitemapData.php it should have to have set $timestamps = true;

<?php 

 class SitemapData extends Eloquent {

        public $timestamps = true;
}
like image 5
Saeed Avatar answered Nov 17 '22 09:11

Saeed