我的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'));
}
我试图让它重定向到'dashboard'而不是'profile.index',如果它是Auth用户的页面而不是像普通的非身份验证配置文件那样拉起来,但似乎无法得到它上班。关于如何修复这个小bug的任何想法?
答案 0 :(得分:0)
您尝试将当前用户对象与请求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'));
}
答案 1 :(得分:0)
您只能通过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'));
}
}
让我知道它是否有帮助!