【问题标题】:How to make auth as user with route id in laravel如何在laravel中以具有路由ID的用户身份进行身份验证
【发布时间】:2019-12-28 03:10:52
【问题描述】:

我想在我的登录系统中使用两个角色的身份验证:

  • 管理员
  • 用户。

当我将路由重定向到用户时,它失败了。

我的控制器:

public function profile($id)
{
    $santri = Santri::find($id);

    return view('santri.profile', ['santri'=>$santri]);
}

我的路线:

Route::group(['middleware' => ['auth', 'checkRole:admin,user']], function () {
    Route::get('/santri/{id}/profile', 'SantriController@profile')->name('profiluser');
});

我如何检查角色:

{
    $santri = Santri::all();

    if(in_array($request->user()->role,$roles))
    {
        return $next($request);
    }

    return redirect()->route('profiluser', $santri);
}

错误:

缺少 [Route:profiluser] [URI: santri/{id}/profile] 的必需参数。

【问题讨论】:

    标签: php laravel authentication laravel-5 laravel-5.8


    【解决方案1】:

    错误信息:

    缺少 [Route: profileuser] [URI: santri/{id}/profile] 的必需参数。

    告诉您缺少此路由的参数:profiluser

    正如您在此处看到的那样,您没有使用正确的参数调用路由,而是尝试传递整个对象而不是 id,所以不是这个:

    return redirect()->route('profiluser', $santri);
    

    这样做:

    return redirect()->route('profiluser', $santri->id);
    

    但是由于您已经传递了整个对象,您也可以这样做,我们将其称为方法 B。

    在这里你想使用传递的 id 找到模型:

    public function profile($id)
    {
        $santri = Santri::find($id);
    
        return view('santri.profile', ['santri'=>$santri]);
    }
    

    但既然你已经传递了整个对象,你可以这样做:

    public function profile(Santri $santri)
    {
        return view('santri.profile', ['santri' => $santri]);
    }
    

    或者这个,在我看来更干净:

    public function profile(Santri $santri)
    {
        return view('santri.profile', compact('santri'));
    }
    

    【讨论】:

    • 恕我直言,您是对的,但将public function profile(Santri $santri) 更改为public function profile(Santri $id),注入的变量名称应与隐式绑定工作的参数名称匹配。
    【解决方案2】:

    您需要传递 $santry->id 而不仅仅是 $santry。将行更改为:

    return redirect()->route('profiluser', [$santri->id]);
    

    【讨论】:

      【解决方案3】:

      根据您的路线:

      Route::get('/santri/{id}/profile', 'SantriController@profile')->name('profiluser');
      

      您必须传递用户 ID,如下所示:

      return redirect()->route('profiluser', ['id' => $request->user()->id]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-08
        • 2016-10-08
        • 2017-12-05
        • 1970-01-01
        • 1970-01-01
        • 2019-10-10
        相关资源
        最近更新 更多