我创建了一个IndexController.php类,用于处理与用户相关的数据控制。
所以我可以通过以下方法获取当前登录的用户。但是url是一种通用url。我希望它是基于登录用户的自定义url。例如,如果userx以用户身份登录,则他的配置文件应显示为http://127.0.0.1:8000/user/userx.我该怎么解决这个问题?
IndexController.php
class IndexController extends Controller{
public function Index(){
return view('dashboard.index');
}
public function userLogout(){
Auth::logout();
return Redirect()->route('login');
}
public function userProfile(){
$id = Auth::user()->id;
$user = User::find($id);
return view('dashboard.profile',compact('user'));
}
}
Web.php
Route::get('/user/profile',[IndexController::class, 'userProfile'])->name('user.profile');
创建一个带有参数的路由,然后使用该变量获取配置文件:
Route::get('/user/profile/{username}',[IndexController::class, 'userProfile'])->name('user.profile');
然后在您的控制器中,您应该可以在方法参数中访问此用户名:
public function userProfile(Request $request, $username)
{
$user = User::query()->where('username', $username)->firstOrFail();
// ...
}
如果您想在自己的配置文件页面上添加额外功能(如更改密码等(,则必须检查已验证的用户Auth::user()
。或者,当您想要更改自己的配置文件时,您可以保留默认的/user/profile
路由作为要访问的URL。有多种方法可以解决这个问题:(
您需要检查两个Laravel概念:
- 路由模型绑定
- 命名路线
路线
Route::get('/user/{profile}',[IndexController::class, 'userProfile'])->name('user.profile');
控制器
public function userProfile(User $profile){
// Check if $profile is the same as Auth::user()
// If only the user can see his own profile
$id = Auth::user()->id;
$user = User::find($id);
return view('dashboard.profile',compact('user'));
}
刀片
<a href="{{ route('user.profile', ["profile" => $user->id]) }}"> See profile </a>
或
<a href="{{ route('user.profile', ["profile" => Auth::user()->id]) }}"> See profile </a>