Less Known Eloquent Model Actions

LaravelPosted on

There are some common, well knowns actions that we can perform on our models. However, you may find some interesting things only when you dig a bit deeper.  Let’s cover some less known model actions.

#1 Check for a model’s existence

If you need to know, if a model exists, you can use the exists() method. It returns only a boolean value, instead of the model itself. So it’s different than the find() method.

<?php

// Determine if the user exists
User::where('email', '[email protected]')->exists();

#2 Check if the model is trashed

As we know, we can use the SoftDeletes trait. It offers the possibility, to check if the given model is trashed or not. Behind the scenes, the trashed() method checks if the model’s deleted_at column has a date or it is null.

<?php

// Determine if the model is trashed
$post->trashed();

#3 Permanently delete a trashed model

A model that uses the SoftDeletes trait is not getting deleted when we call the delete() method on it. It sets only the deleted_at columns value. But what if we want to delete the model permanently? We can use the forceDelete() method.

<?php

// Delete the model permanently
$product->forceDelete();

// A little trick, do determine when to soft- and force delete a model
$product->trashed() ? $product->forceDelete() : $product->delete();

#4 Restore a trashed model

We can restore a trashed model, by calling the restore() method. It sets the deleted_at column to null.

<?php

// Restore the model
$food->restore();

#5 Clone a model

In some cases, we need to clone a model. We can copy all the attributes of the source model, by calling the replicate() method.

<?php

// Deep copy the model
$new = $model->replicate();
Tip: If you want to recreate all the relationships as well, you need to loop through and recreate them manually.

Summary

Eloquent has many nice features. Many of them are quite less known. It’s a good point to dig deeper into the documentation, in forums and in the code itself. You may find some new and interesting features that you can use for your next project.

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in Laravel category