Soft deleted models refer to a feature in Laravel that allows you to "soft delete" records from your database instead of permanently deleting them. This means that when you delete a record, it is not immediately removed from the database, but rather marked as deleted by setting a timestamp in the deleted_at column.
To use soft deleted models in Laravel, you need to perform the following steps:
- Add a
deleted_atcolumn to your database table. You can do this by creating a new migration or modifying an existing one. For example, if you have auserstable, you can add thedeleted_atcolumn like this:
Schema::table('users', function (Blueprint $table) {
$table->softDeletes();
});
- In your model class, use the
SoftDeletestrait and specify thedeleted_atcolumn. For example, if you have aUsermodel, you can add theSoftDeletestrait like this:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}
- Now, when you delete a record using the
delete()method on a model instance, it will be soft deleted. For example:
$user = User::find(1);
$user->delete();
- To retrieve soft deleted records, you can use the
withTrashed()method on your query. For example, to retrieve all users, including soft deleted ones:
$users = User::withTrashed()->get();
- To retrieve only soft deleted records, you can use the
onlyTrashed()method on your query. For example, to retrieve all soft deleted users:
$users = User::onlyTrashed()->get();
- To restore a soft deleted record, you can use the
restore()method on a model instance. For example, to restore a soft deleted user:
$user = User::withTrashed()->find(1);
$user->restore();
That's it! Soft deleted models provide a convenient way to handle deleted records without permanently removing them from the database.