Launching Drycomponents - Get Free HTML/React Components built using TailwindCSS

Decoding Laravel : Eloquent touch()

Today we are going to see about laravel eloquent touch method. Touch touch() is a method offered by eloquent that is used to update the updated_at field on the database table for the given model. For example, if you have a login system and you wanted to update the updated_at field whenever a user logs in (as last login), then you do this by $user->touch(). Laravel updates the updated_at field to current date and time.

Eloquent Model

We knew that all of our models extend Laravel core Model Illuminate\Database\Eloquent\Model. Model offers touch() method. We will see how this works.

First laravel checks whether our model has timestamps columns. If not, it’ll simply return false i.e., it doesn't have to do anything. If we do have timestamps, then it calls updateTimestamps() method.

$this->freshTimestamp() is nothing but the new instance of Carbon

Then it checks whether updated_at field is dirty(i.e., whether it has been modified already). If true, laravel will not perform any action and prevent query execution. Else, we will update the updated_at field. So, lets break isDirty() step by step.

Here $this->getDirty(), laravel checks for two things.

  1. Check if any new attribute has been added to attributes array apart from original attributes
  2. Checks whether old attributes and new attributes are same and numerical equivalent

Then it checks whether parameters passed to this function is null. If true, it will check whether count of modified attributes is greater than zero and return true

If attributes are not null, then

We are checking if it is array, if not, we are converting it to array by calling func_get_args() method which returns the params as array.

Then, we are returning true if modified variable(updated_at) is found on attributes list and false otherwise.

If we get false(i.e., updated_at field is not modifed), then $this->setUpdatedAt() is called

After updating the updated_at field, we are checking if our model has been created and saved before. If not, we are going to update created_at field as well.

Thats it! This is how laravel eloquent touch works under the hoods.

Would like to hear more from me?

Consider Signing up. No spam ever.

Name

Email

Topic