0 Shares 10465 Views

Laravel Soft Delete

This Is How To Do a Laravel Soft Delete

We will talk about a little more specific issue today. We do not want our data in our database to be completely deleted. For this reason, we will talk about  Soft Delete on Laravel.

Note: I will tell the story through the blog article system. I continue the narration, thinking that you are creating a Laravel Project. Lecture design, design, and so on. I will not use things. I will only talk about Soft Delete.

Let’s define a few routes first.

# /routes/api.php
        Route::group(['prefix' => 'blog'], static function () {

            Route::get('all', 'BlogController@all');

            Route::get('list', 'BlogController@list');

            Route::get('only-trashed', 'BlogController@onlyTrashed');

            Route::post('store', 'BlogController@store');

            Route::delete('delete/{id}', 'BlogController@delete');

            Route::patch('restore/{id}', 'BlogController@restore');

        });

 

Primarily we added a prefix named Blog and in it

  • lists
  • List Deleted Only
  • Save
  • Clear
  • Add back

We have defined our operations. Now let’s create one Model and our associated Controller and Migration files.

php artisan make:model Blog -mc

Then let’s define our methods in Controller. After the edits, the Blog Controller should look like this.

<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreRequest;

class BlogController extends Controller

{

    public function all()

    {

    }

    public function list()

    {

    }

    public function store(StoreRequest $request)

    {

    }

    public function delete(int $id)

    {

    }

    public function restore(int $id)

    {

    }

    public function onlyTrashed()

    {

    }

}

 

Here I made use of FormRequest feature to make control operations comfortable. Those who don’t know can check out my previous article here. Then we edit our migration file and then run it.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBlogsTable extends Migration

{

    /**
     * Run the migrations.
     *
     * @return void
     */

    public function up()

    {

        Schema::create('blogs', function (Blueprint $table) {

            $table->id();

            $table->string('title', 60);

            $table->text('content');

            $table->integer('views', false)->default(0);

            $table->string('author');

            $table->timestamps();

            /**
             * This part is necessary for us to use the soft-delete feature.
             */

            $table->softDeletes();

        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */

    public function down()

    {

        Schema::dropIfExists('blogs');

    }

}

 

The softDeletes method we added here is required to create a column named deleted_at into the blogs table. In this way, we will be able to use our soft-delete feature. Then we update our Model file as follows.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Blog extends Model

{

    use SoftDeletes;

    protected $fillable = [

        'title', 'content', 'author'

    ];

}

Here SoftDelete trait will manage the deleted_at column and other features for us. Now let’s fill in the methods we created into the Controller. It should look like this.

<?php

namespace App\Http\Controllers;

use App\Blog;
use App\Http\Requests\{StoreRequest};
use Illuminate\Http\JsonResponse;

class BlogController extends Controller

{

    /**
     * Returns all posts, including those that have been deleted.
     * @return JsonResponse
     */

    public function all()

    {

        /**
         * WithTrashed, we have added the deleted articles to the query.
         */

        $blogs = Blog::withTrashed()->get();

        return response()->json($blogs, 200);

    }

    /**
     * @return JsonResponse
     * Returns all blog posts except deleted ones.
     */

    public function list()

    {

        return response()->json(Blog::all(), 200);

    }

    /**
     * @param StoreRequest $request
     * Saves a new blog post.
     * @return JsonResponse
     */

    public function store(StoreRequest $request)

    {

        $store = [

            'title' => $request->post('title'),

            'content' => $request->post('content'),

            'author' => $request->post('author') ?? "Anonymous",

        ];

        $result = Blog::create($store);

        return response()->json($result, 200);

    }

    /**
     * Deletes a blog post.
     * @param Int $id
     * @return JsonResponse
     */

    public function delete(int $id)

    {

        $blog = Blog::findOrFail($id);

        $blog->delete();

        return response()->json(['deleted_at' => $blog->deleted_at], 200);

    }

    /**
     * Brings back a deleted blog post.
     * @param Int $id
     * @return JsonResponse
     */

    public function restore(int $id)

    {

        /**
         * Find content only among those deleted.
         */

        $blog = Blog::onlyTrashed()->findOrFail($id);

        $blog->restore();

        return response()->json($blog, 200);

    }

    /**
     * It only fetches deleted blog posts.
     */

    public function onlyTrashed()

    {

        /**
         * Here we call onlyTrashed as an extra.
         */

        $blog = Blog::onlyTrashed()->get();

        return response()->json($blog, 200);

    }

}

 

Thus, we have completed our transactions. There are two methods to be aware of here, one of which is withTrashed (). This method allows us to include deleted ones in the query. Another is the onlyTrashed () method we use to fetch only deleted ones. If you want to remove it from your database, you can use forceDelete but I don’t recommend it. Here we come to the end of our article.

Good and Error Free Coding for Everyone :)

free trial CDN

 

You may be interested

The Ultimate CDN (Content Delivery Network) Guide
CDN
5437 views
CDN
5437 views

The Ultimate CDN (Content Delivery Network) Guide

Nadia Benslimane - August 3, 2020

The Ultimate CDN Guide- Everything About Content Delivery Network You probably know what CDN (Content Delivery Network) stands for. You may also be aware of its full definition,…

The Essential CDN Glossary
CDN
9767 views
CDN
9767 views

The Essential CDN Glossary

Nadia Benslimane - November 21, 2019

Why Have We Decided To Create a CDN Glossary? Whether you are new to the world of CDN, or have been involved in it for years, there…

HTTP Live Streaming
CDN
259 views
CDN
259 views

HTTP Live Streaming

medianova - November 1, 2021

Introduction To HTTP Live Streaming What Is HTTP Live Streaming (HLS)? HLS (HTTP live streaming) is one of the most widely used video streaming protocols. Although live…

All You Need to Know About Round-Trip Time
CDN
234 views
CDN
234 views

All You Need to Know About Round-Trip Time

Gizay Yalçın - October 20, 2021

What exactly is RTT?  Round-trip time (RTT) is a networking metric that measures in milliseconds the time it takes for a data packet to be sent and…

SD-WAN in CDNs
CDN
262 views
CDN
262 views

SD-WAN in CDNs

Gizay Yalçın - October 20, 2021

Why Does Your Business Need SD-WAN in CDNs? What is SD-WAN? As the name implies, a software-defined wide area network (SD-WAN) is a virtual wide area network…

Most from this category

The Ultimate CDN (Content Delivery Network) Guide
CDN
5437 views
5437 views

The Ultimate CDN (Content Delivery Network) Guide

Nadia Benslimane - August 3, 2020
The Essential CDN Glossary
CDN
9767 views
9767 views

The Essential CDN Glossary

Nadia Benslimane - November 21, 2019
Health Check Backup Origin
CDN
234 views
234 views

Health Check Backup Origin

Nilgün Ünsal - October 17, 2021
DDoS Attack Trends in 2021
CDN
450 views
450 views

DDoS Attack Trends in 2021

Elif Ak - October 17, 2021
Web Application Firewall
Uncategorized
28 views
28 views

Web Application Firewall

Aykut Teker - September 30, 2021
Web Application Firewall
CDN
600 views
600 views

Web Application Firewall

Aykut Teker - September 29, 2021