Database Eloquent ORM Soft Deleting / Trashing

Update your model to include soft deletes like this:

use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
    protected $dates = ['deleted_at'];

}

Now create a migration (name of file with flag for name of database table to add onto)

php artisan make:migration add_deleted_at_column_to_posts_tables --table=posts

Now add your new columns to this file in the up and down functions like so:

    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->softDeletes();
        });
    }


    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('deleted_at');
        });
    }

Get the new column to show up with:

php artisan migrate

To your routes file add this to soft delete an item in the database:

Route::get('/softdelete', function(){
    Post::find(11)->delete();
});

Now running queries like Post::all() won’t find the soft deleted items anymore so check the database directly.

Leave a Reply

Your email address will not be published.