How to use timestamps to automatically update "created_at" and "updated_at" columns in Eloquent in Laravel?

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.

  1. Add the $timestamps property to your Eloquent model:
public $timestamps = true;
  1. Make sure that the corresponding columns (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(); }); }
  1. Now, whenever you create or update a record using your model, the "created_at" and "updated_at" columns will be automatically maintained.

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.

  1. If you want to update only the "updated_at" timestamp without modifying any other attributes, you can call the 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.