Everything you need as a full stack developer

Eloquent Touch with updating timestamps

- Posted in Laravel by

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.

Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more