TL;DR Eloquent automatically sets created_at and updated_at timestamps when creating or updating records, but can also be manually updated using $touches.
Eloquent's Magic Trick: Updating Timestamps
As a Laravel developer, you're likely familiar with Eloquent, the ORM (Object-Relational Mapping) tool that simplifies your interactions with the database. But have you ever stopped to think about how it handles timestamps? In this article, we'll delve into the world of timestamp updating and explore some lesser-known features of Eloquent.
What are Timestamps?
Timestamps, also known as "update_at" or "created_at", are special columns in your database that store the exact time a record was created or last updated. These timestamps serve multiple purposes:
- Auditing: They help track changes made to a record over time.
- Data synchronization: They enable seamless data transfer between different systems or environments.
- Performance optimization: They can be used to implement caching and reduce database queries.
How Eloquent Handles Timestamps
By default, Laravel's Eloquent sets the created_at timestamp automatically when you create a new model instance. This is achieved through the timestamps() method in your model file:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $fillable = [
// ...
];
public $timestamps = true;
}
The $timestamps property is a boolean that, when set to true, enables timestamp updating for the model. This means Eloquent will automatically populate the created_at and updated_at columns whenever you create or update a record.
Updating Timestamps
Now that we've covered how timestamps are set by default, let's discuss some scenarios where you might want to manually update them:
- Manual updating: In certain situations, you may need to update a timestamp manually. For example, when implementing a custom auditing system.
- Mass updates: Eloquent provides the
update()method for bulk updating records. However, this doesn't update timestamps.
To overcome these limitations, you can use Eloquent's $touches property:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $fillable = [
// ...
];
public function setUpdatedAtAttribute($value)
{
return parent::setUpdatedAtAttribute($value);
}
protected $touches = ['category'];
}
In the above example, whenever you update a Category record (which has a relationship with Post), Eloquent will automatically update the updated_at timestamp for all associated Post records.
Best Practices and Conclusion
While Eloquent's built-in timestamp handling is convenient, it's essential to understand how it works. By leveraging features like $touches, you can create more sophisticated models that adapt to your application's specific requirements.
