Laravel - how to bind soft deleted route and model

Viewed 48

I'm using soft delete in model Article, but in model Comment not use soft delete. I'm also customize the key using slug column in model Article. If the article is deleted, I want still show the comment. But when article is deleted, show method always return 404.

public function show(Article $article, Comment $comment)
    {
        if ($article->id != $comment->article_id)
            throw new NotFoundHttpException('Record Not Found.');

        return $this->success(['comment => $comment']);
    }

How to fix this?

2 Answers

Your question statement is not defining the problem you should ask how to bind soft deleted route and model.

Laravel provide ->withTrashed() method for this so it also bind soft deleted models in route.

web.php

user App/Http/Controller/ArticleController;

Route::get('article/{article}', [ArticleController::class, 'show'])->name('article.show')->withTrashed();

But this method added in Laravel 8.55 If you have older version so you can simply find model in controller without route model binding.

ArticleController.php

public function show($article, App/Comment $comment)
{
    $article = App/Article::withTrashed()->findOrFail($article);

    if ($article->id != $comment->article_id) {
        throw new NotFoundHttpException('Record Not Found.');
    }

    return $this->success(['comment => $comment']);
}

Or you can also use Explicit Binding for specific model in RouteServiceProvider.

public function boot()
{
    parent::boot();

    Route::bind('article', function ($id) {
        return App\Article::withTrashed()->find($id) ?? abort(404);
    });
}

And you can also use onlyTrashed() method in explicit binding in case you use separate route for trashed models.

If you want to get deleted records as well, use the method withTrashed Your code should look something like this:

Article::withTrashed()->find($id);

Hope it help u and happy coding !

Related