Boost Your Laravel App’s Efficiency with Soft Deletes.
Laravel has a strong feature called soft deletes
that lets you keep data even after it has been successfully removed from view. Soft deletes identify records as deleted but leave them in the database; they can be restored if necessary. This strategy can enhance your application’s effectiveness and preserve data integrity.
- Understanding Soft Deletes
Laravel adds a deleted_at
column to your database table when you enable soft deletes. Laravel indicates that a record is removed by setting its deleted_at value to the current timestamp rather than deleting it.
2. Setting Up Soft Deletes
Step 1: Add deleted_at
Column
First, you need to add a deleted_at
column to your database table. This can be done by creating a migration.
php artisan make:migration add_deleted_at_to_users_table --table=users
Then, in the generated migration file:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->softDeletes();
});
}
Run the migration:
php artisan migrate
Step 2: Update Your Model
In your Eloquent model (e.g., User
), use the SoftDeletes
trait to enable soft deletes:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at']; // Specify the column name
}
Here’s a breakdown of what each part does:
- use Illuminate\Database\Eloquent\Model
This line imports the `Model` class from Laravel’s Eloquent ORM. By extending this class, the `User` class inherits the functionality for interacting with the database. - use Illuminate\Database\Eloquent\SoftDeletes
This line imports theSoftDeletes
trait, which enables soft deletes for theUser
model. Soft deletes allow you to keep a record of deleted entries in the database by setting adeleted_at
timestamp instead of permanently removing the record. - class User extends Model
This line defines theUser
class, which extends theModel
class. This meansUser
inherits all the features of Eloquent models, such as querying the database and working with relationships. - use SoftDeletes
This line applies to theSoftDeletes
trait to theUser
model, enabling soft delete functionality. With this trait, theUser
model will now handle deletions by setting a timestamp in thedeleted_at
column rather than removing the record from the database. - protected $dates = [‘deleted_at’]
This line specifies that thedeleted_at
column should be treated as a date. Laravel needs to know that `deleted_at` is a date column to properly handle it when performing soft deletes and other date-related operations.
In summary, this User
model uses soft deletes, which means when you delete a user, the record is not permanently removed from the database. Instead, Laravel sets a timestamp in the deleted_at
column, allowing you to later restore the record if needed.
3. Using Soft Deletes.
Soft Deleting a Record
To soft delete a record, use the delete
method:
$user = User::find(1);
$user->delete();
Restoring a Soft Deleted Record
To restore a soft deleted record, use the restore
method:
$user = User::withTrashed()->find(1);
$user->restore();
Permanently Deleting a Record
If you want to permanently delete a record from the database:
$user = User::withTrashed()->find(1);
$user->forceDelete();
4. Querying Soft Deleted Records
Retrieving Only Active Records
By default, Laravel queries only the non-deleted records:
$users = User::all();
Including Soft Deleted Records
To include soft deleted records in your query, use the withTrashed
method:
$users = User::withTrashed()->get();
Retrieving Only Soft Deleted Records
To get only the soft deleted records, use the onlyTrashed
method:
$deletedUsers = User::onlyTrashed()->get();
5. Customizing the Deleted Column Name
By default, Laravel uses deleted_at
as the column name. If you want to customize this, override the getDeletedAtColumn
method in your model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
// Use the SoftDeletes trait to enable soft delete functionality in this model
use SoftDeletes;
/**
* Override the default 'deleted_at' column name.
* By default, Laravel uses 'deleted_at' for soft deletes,
* but you can customize it by overriding the getDeletedAtColumn method.
*
* @return string
*/
public function getDeletedAtColumn()
{
// Specify the custom column name for soft deletes
return 'custom_deleted_at';
}
}
Make sure to update the column name in your migration accordingly.
6. Handling Soft Deletes in Relationships
Soft deletes can also be used in relationships. For example, if a Post
has many Comments
and you want to include soft deleted comments in a post’s comments, use the withTrashed
method on the relationship:
public function comments()
{
return $this->hasMany(Comment::class)->withTrashed();
}
Conclusion
With Laravel, soft deletes offer a reliable method of managing data without erasing it. You can make sure that your application processes data more effectively and maintains crucial information by putting these pointers and techniques into practice.
If you love the content and want to support more awesome articles, consider buying me a coffee! ☕️🥳 Your support means the world to me and helps keep the knowledge flowing. You can do that right here: 👉 Buy Me a Coffee
Check out this awesome article that breaks it down in a super-duper easy-to-understand way. 📖✨ You can find it right here: 👉Mastering Laravel Macros: The Ultimate Developer’s Guide
And don’t forget to share your thoughts and feedback! 🤜💬 Let’s learn and grow together! 😊💡 #Laravel #Macros #LearnAndGrow 🌟
🚀 Stay Connected with Me! 🚀
Don’t miss out on more exciting updates and articles!
Follow me on your favorite platforms:
🔗 LinkedIn
📸 Instagram
🧵 Threads
📘 Facebook
✍️ Medium
Join the journey and let’s grow together! 🌟