SoftDelete

How to use Softdelete

Laravel SoftDelete is a way to delete records symbolically since it will not delete your data entirely. Still, it will mark them with a date on which you decided to delete them visually from your projects, leaving them on standby for anything in the database.

What would happen if you deleted some data by mistake and don't have a backup of them? of course you start sweating, right, because with Laravel SoftDelete we can recover them without losing them by deleting them headfirst.

 

Ok, to start first we have to use in our migrations almost at the end where the timeStamps are the following code

 

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->foreignId('current_team_id')->nullable();
            $table->string('profile_photo_path', 2048)->nullable();
            $table->softDeletes();
            $table->timestamps();
        });

as you can see we have in the table a column called softdeletes() and in the user model we have to make use of the SoftDeletes trait

namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable
{
    use SoftDeletes;

With these simple and practical steps, we can make SOFT deletions in our database without having to make the permanent deletion of a record. This helps us because we do not have to put extra columns in our database to know if a record is active or not, and even more, we will know the tracking of the date on which the deletion was registered.

If we want to see the deleted records marked with Laravel SoftDelete we must use the following statements.

$user->trashed();

We can also make use of the method restore data deleted by Laravel SoftDelete

$user->restore();

This method is also used in queries to restore a lot of data.

User::withTrashed()
       ->restore();

To get records with temporarily deleted data we use

User::withTrashed()->get();

When we want to permanently delete data, we can force the deletion using

$user->forceDelete();
If we want to get only temporarily deleted data, we can retrieve it with the help of the onlyTrashed() method.
User::onlyTrashed()->get();

 

We can realize that the framework is prepared to make our life easier, I hope this helps you, soon I will be uploading more content that helps me a lot in my day to day.

 

Au-revoir a toute le monde !!

 

 

Para crear un comentarío debes registrarte

Login Registro

Comentarios Relacionados

No hay comentarios para el post por el momento