![](/img/trans.png)
[英]Is there a better way of getting the profile image of the currently logged in user with Laravel?
[英]Laravel how to customize user profile url based on currently logged in user
我創建了一個 IndexController.php class 來處理與用戶相關的數據控制。
所以我可以通過以下方法獲取當前登錄的用戶。 但是 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');
然后在您的 controller 中,您應該可以在方法 arguments 中訪問此用戶名:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.