How to Create a Trashed Entry on Laravel

I was looking at the documentation for laravel as I am learning this framework. One cool thing I saw is how to modify the database for trashed elements. Here are the steps to get started

I was looking at the documentation for laravel as I am learning this framework. One cool thing I saw is how to modify the database for trashed elements. Here are the steps to get started

First, we must run a command to create the migration table for the table you need. In this scenario, we are doing it on the posts table

php artisan make:migration add_soft_delete_to_posts_table --table=posts

After that, you will see a new migration we will modify it to look like this. 

class AddSoftDeleteToPostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
           $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            //
           $table->dropSoftDeletes();
        });
    }
}

In our models, we will adjust it to add the soft deletes.

<?php

namespace AppModels;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\EloquentModel;
use Illuminate\Database\EloquentSoftDeletes;

class Post extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = [
    	'title', 'description', 'content', 'image', 'published_at'
    ];
}

In our controller we will use the following

public function destroy($id)
    {
        //
        $post = Post::withTrashed()->where('id', $id)->firstorFail();

        if($post->trashed()){
            $post->forceDelete();
        } else {
            $post->delete();
        }

        session()->flash('success', 'Deleted Successfully.');
        return redirect(route('posts.index'));
    }