【问题标题】:How to stop Auth user from visiting own page with non auth user privileges in laravel?如何阻止 Auth 用户在 laravel 中以非 auth 用户权限访问自己的页面?
【发布时间】:2017-07-05 22:42:19
【问题描述】:

我的 laravel 应用程序是一个社交媒体网站。这是访问另一个 laravel 用户个人资料的路线

Route::get('/dashboard/{id}', [
'uses' => 'UserController@getProfile',
'as' => 'profile.index',
'middleware' => 'auth'
]);

它工作得很好。但是,我发现了一个错误,当我在路由中输入 Auth 用户的 ID 时,我会被带到同一个页面,然后我可以将自己添加为朋友,我不希望这种情况发生。如果我正在访问自己的个人资料,我宁愿回到主屏幕。

这是控制器:

 public function getProfile($id)
{

    if(Auth::user() === $id)
        redirect('dashboard');

    $user = User::where('id', $id)->first();

    $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
    $photos = Photo::paginate(6);
    return view('profile.index',compact('user','posts', 'photos'));

}

我试图让它重定向到“仪表板”而不是“profile.index”,如果它是 Auth 用户的页面,而不是像普通的非身份验证配置文件那样拉起,但似乎无法得到它去工作。关于如何修复这个小错误的任何想法?

【问题讨论】:

    标签: php laravel authentication routes


    【解决方案1】:

    您可以通过Auth::user() 获取用户实例,而不仅仅是用户 ID。您正在将实例与数值进行比较。不起作用。您必须使用Auth::id()Auth::user()->id 来获取登录用户的ID。以下代码适用于您的情况。

    public function getProfile($id)
    {
    
        if(Auth::id() == $id)
        {
            redirect('dashboard');
        }
        else
        {
            $user = User::where('id', $id)->first();
            $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
            $photos = Photo::paginate(6);
            return view('profile.index',compact('user','posts', 'photos'));
        }
    }
    

    如果有帮助请告诉我!

    【讨论】:

    • 它停止将 Auth 配置文件作为常规配置文件提取,但现在我没有重定向,而是得到一个空白页面。
    • 我现在知道了,只需要在重定向中添加返回 :) 谢谢!
    • 是的!这就是您需要的答案。
    【解决方案2】:

    您尝试将当前用户对象与请求 id 进行比较,请尝试以下代码:

    public function getProfile($id)
    {
        if(Auth::id() === $id) {
            redirect('dashboard');
        }
    
        $user = User::where('id', $id)->first();
    
        $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
        $photos = Photo::paginate(6)
    
        return view('profile.index',compact('user','posts', 'photos'));
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 2021-05-20
      • 1970-01-01
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多