0

I have recently added a new migration to my database which in its simplest form does something like this

If(Schema::hasTable('some_table')){
    Schema::table('some_table', function (Blueprint $table) {
        $table->dateTime('last_updated')->nullable(false)->useCurrent()->change();
    });
}

According to this answer on SE, Laravel should automatically create and updated the last_record column for me but I am testing this in MySQL 5.7.31 and this is definitely not the case for me. I am using Laravel 7.5 and my PHP version is 7.3.21.

Meanwhile, adding CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP manually to my database failed as well. So, it seems that it might be an issue with my MySQL database instead of Laravel itself. So, I have two questions:

Is it possible to somehow use Laravel/PHP to always add a default value to a field when nothing is passed on insert or update?

Edit: @lagbox asked about how I am saving/updating records in my database. Here is how

$record= TableModel::where('blah', $blah)
                ->first();

if($record){
    $record->update([
         'blah1' => $blah1,
         'blah2' => $blah2
    ]);
}
stressed out
  • 522
  • 6
  • 24
  • Eloquent will automatically handle `created_at` and `updated_at` – lagbox Sep 14 '20 at 16:13
  • @lagbox Yes, but my field is `last_updated`, not `updated_at`. Is it possible to tell Eloquent to change the default name? – stressed out Sep 14 '20 at 16:15
  • 1
    yes if you check `Illuminate\Database\Eloquent\Model` you will see `const UPDATED_AT = 'updated_at';` so you can define that on your Model as you like https://laravel.com/docs/7.x/eloquent#eloquent-model-conventions Model Conventions - Timestamps – lagbox Sep 14 '20 at 16:16
  • @lagbox Thank you. I'm sorry if there's something really trivial that I'm missing, but I added ```const UPDATED_AT = 'last_updated';``` to my model for my table, but it's still not working. :| – stressed out Sep 14 '20 at 16:20
  • how are you saving/updating this record? – lagbox Sep 14 '20 at 16:26
  • @lagbox I added how I am updating my record. I am basically calling update on my model which extends ```Illuminate\Database\Eloquent\Model```. – stressed out Sep 14 '20 at 16:32
  • you didn't set `$timestamps = false;` on the model did you? – lagbox Sep 14 '20 at 16:32

1 Answers1

2

You can override the fields that are used for the created_at and updated_at timestamps on the Model that Eloquent will automatically handle:

const UPDATED_AT = 'last_updated';

You can also disable a particular timestamp by setting the const to null:

const CREATED_AT = null;

Laravel 7.x Docs - Eloquent - Model Conventions - Timestamps UPDATED_AT CREATED_AT

lagbox
  • 48,571
  • 8
  • 72
  • 83