Php 如何在laravel中阻止身份验证用户以非身份验证用户权限访问自己的页面?

Php 如何在laravel中阻止身份验证用户以非身份验证用户权限访问自己的页面?,php,laravel,authentication,routes,Php,Laravel,Authentication,Routes,我的laravel应用程序是一个社交媒体网站。以下是访问其他laravel用户个人资料的路线 Route::get('/dashboard/{id}', [ 'uses' => 'UserController@getProfile', 'as' => 'profile.index', 'middleware' => 'auth' ]); 它很好用。然而,我发现了一个bug,当我在路由中输入Auth用户的ID时,我会被带到同一个页面,在那里我可以添加自己作为朋友,我不希望发生这

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

Route::get('/dashboard/{id}', [
'uses' => 'UserController@getProfile',
'as' => 'profile.index',
'middleware' => 'auth'
]);
它很好用。然而,我发现了一个bug,当我在路由中输入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'));

}

我试图让它重定向到“dashboard”而不是“profile.index”,如果它是授权用户的页面,而不是像普通的非授权配置文件一样打开,但似乎无法让它工作。关于如何修复这个小错误有什么想法吗

如果尝试将当前用户对象与请求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'));
}

您通过
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配置文件作为常规配置文件进行拉拽,但是现在我没有重定向,而是得到了一个空白页面。我现在得到了它,只是需要将return添加到重定向中:)谢谢!是的!!这就是你需要的答案。