【问题标题】:How to user route model binding in Laravel for Pivot model如何在 Laravel 中为 Pivot 模型用户路由模型绑定
【发布时间】:2019-06-06 02:40:42
【问题描述】:

Laravel v: 5.7

PHP v: 7.2.10

路由路径为:admin/apartments/{apartment}/associations/{association}/association-users/{association_user}
获取网址:http://127.0.0.1:8000/admin/apartments/1/associations/1/association-users

枢轴模型:AssociationUser

App\Providers\RouteServiceProvider,我已经添加了

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

        Route::bind('association-user', function ($value) {
            return App\pivotes\AssociationUser::where('association_id', request()->route()->parameter('association')->id)->where('user_id', auth()->id())->first() ?? abort(404);
        });
    }

路线创建

route('apartments.associations.association-users.show', ['apartment' => $associationUser->association->apartment, 'association' => $associationUser->association, 'association_user' => $associationUser ])

【问题讨论】:

  • 什么问题,你总是得到 404?
  • @thefallen 我得到的是索引页面而不是显示页面,你可以看到我在那里缺少模型。
  • 我会将这个逻辑移到中间件或控制器方法中,因为使用路由绑定,这个东西是隐藏的,就像魔法一样,但它很糟糕。
  • @thefallen 为枢轴模型获取路由模型绑定的正确方法是什么?
  • 您只需将其绑定到正确的模型类,并在中间件或控制器中验证它们之间是否存在关系。

标签: php laravel-5 eloquent pivot-table php-7.2


【解决方案1】:

如果我没看错,association_user 数据透视表应该有 association_id 和 user_id 并且两者的组合都是唯一的,所以在你的路由中已经有 {association} 模型,所以我相信你可以使用

public function getRouteKeyName()
{
    return 'user_id';
}

在您的模型类中,user_id 将出现在您的 url 中,您将拥有关联和用户模型的组合。

不需要

 Route::bind('association-user', function ($value) {
            return App\pivotes\AssociationUser::where('association_id', request()->route()->parameter('association')->id)->where('user_id', auth()->id())->first() ?? abort(404);
        }); 

在你的App\Providers\RouteServiceProvider

【讨论】:

    猜你喜欢
    • 2021-05-24
    • 2016-06-04
    • 1970-01-01
    • 2017-06-22
    • 2018-12-17
    • 2020-10-03
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    相关资源
    最近更新 更多