In Laravel, you can use timestamps to automatically update the "created_at" and "updated_at" columns in your Eloquent models by utilizing the $timestamps
property and the touch()
method.
$timestamps
property to your Eloquent model:public $timestamps = true;
created_at
and updated_at
) exist in the table associated with your model. If they don't already exist, you can create them by running a migration:php artisan make:migration add_timestamps_to_table_name --table=table_name
In the generated migration file, add the following code to create the required columns:
public function up()
{
Schema::table('table_name', function (Blueprint $table) {
$table->timestamps();
});
}
For example, to create a new model instance and save it:
$model = new Model;
$model->name = 'John Doe';
$model->save();
This will automatically update both the "created_at" and "updated_at" columns.
touch()
method on the model:$model->touch();
This will update the "updated_at" column to the current timestamp.
Note: When working with timestamps, ensure that the corresponding columns have the correct data types (usually TIMESTAMP
or equivalent) in your database schema.