首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel -如何绑定软删除路由和模型

Laravel -如何绑定软删除路由和模型
EN

Stack Overflow用户
提问于 2022-09-22 04:28:15
回答 2查看 56关注 0票数 0

我在模型文章中使用软删除,但在模型注释中不使用软删除。我还使用模型文章中的段塞列定制了键。如果这篇文章被删除了,我还想显示评论。但是当文章被删除时,show方法总是返回404。

代码语言:javascript
复制
public function show(Article $article, Comment $comment)
    {
        if ($article->id != $comment->article_id)
            throw new NotFoundHttpException('Record Not Found.');

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

怎么解决这个问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-09-22 05:56:04

您的问题陈述并没有定义您应该问如何绑定软删除路由和模型的问题。

Laravel为此提供了->withTrashed()方法,因此它还可以在路由中绑定软删除模型。

web.php

代码语言:javascript
复制
user App/Http/Controller/ArticleController;

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

,但是这个方法是在 Laravel 8.55中添加的,如果您有较早的版本,那么您可以在控制器中找到模型,而无需路由模型绑定。

ArticleController.php

代码语言:javascript
复制
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']);
}

或者您也可以将显式约束用于RouteServiceProvider中的特定模型。

代码语言:javascript
复制
public function boot()
{
    parent::boot();

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

此外,还可以在显式绑定中使用onlyTrashed()方法,以防使用单独的路径处理被破坏的模型。

票数 3
EN

Stack Overflow用户

发布于 2022-09-22 04:38:16

如果您也希望删除记录,请使用withTrashed方法--您的代码应该如下所示:

代码语言:javascript
复制
Article::withTrashed()->find($id);

希望它能帮助你和快乐的编码!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73809355

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档