Laravel eloquent hooking the deleting event

The eloquent model calls several events in the model's lifecycle which you can hook into specific events such as retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored, and replicating.

Let's say whenever I want to delete an article and it automatically deletes article_relate data too. This way I can hook into the deleting event and customize to delete article_relates data when it's article deleted.


In Article.php

Listening to eloquent deleting events and do some logic

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = [
        'title',
        'short_description',
        'content'
    ];

    // This is where you hook into eloquent events and customize the behavior 
    protected static function booted()
    {
        static::deleting(function ($article) {
            if ($article->articleRelates) {
                $article->articleRelates()->delete();
            }
        });
    }

    public function articleRelates()
    {
        return $this->hasMany(ArticleRelate::class);
    }
}
In api.php

Declaring your route for delete article by id

<?php

use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::delete('article/{id}', [ ArticleController::class, 'delete' ]);
In ArticleController.php

Calling eloquent delete function

<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function delete($id)
    {
        return Article::findOrFail($id)->delete();
    }
}

So when you call url/api/article/{id} the article data will be delete with article_relates data.