簡體   English   中英

登錄后將用戶重定向到他們的個人資料

[英]Redirect users to their profile after login

我想將用戶重定向到他們的個人資料,而不是 laravel 的默認 /home 頁面。 我在我的 LoginController 中試過這個: protected $redirectTo = '/profile/{id}'; 但它返回此錯誤:

未找到 id:{id} 的用戶。

這是我的路線: Route::get('/profile/{id}', 'ProfileController@profile');

這是我的配置文件控制器方法:

public function profile(Request $request, $id){
  $User = User::with(['complains'])->find($id);
  if(!$User) return abort(404, 'User with id:'.$id.' not found');

  return view('user.profile')->with(['user' => $User, 'complains' => $User-
  >complains]);
}

您需要傳遞 id protected $redirectTo = '/profile/1'; 要么

$id = Auth::user()->id;
`$redirectTo = '/profile/$id';`

如果您使用 Auth,請在 LoginController 文件中將其用作 Use Auth;

您可以修改 RedirectIfAuthenticated 中間件來實現這一點:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::check()) {
            return redirect()->action('ProfileController@profile', Auth::user()->id);
        }
        return $next($request);
    }
}

這花了我很長時間才得到並且只是為了幫助另一個人。 redirectTo() 方法需要一個字符串作為響應而不是進一步的重定向,因為它本身就是一個重定向,並且從 laravel 文檔中,該函數是字符串類型的。 所以你可以這樣做:

protected function redirectTo()
{
    /*
      You can add any other logic needed to be satisfied here or 
      flash some sessional data here,etc.       
    */
    return 'profile/'.auth()->user()->id;
}

好吧,我知道我遲到了,但我認為這是為其他人留下同樣問題的好地方,所以我做了一個登錄后默認的Route::get('/home', 'PagesController@index'); 然后我在 PagesController 中做了一個函數:

public function index(){
    $user = User::find(auth()->user()->id);
    return view('pages/profile' ['user'=>$user,]); 
}

因此,當您登錄時,它會將用戶數據傳遞到 pages/profile.blade.php 視圖並正常工作。

我認為您不需要在重定向路由上傳遞 id。 您可以在控制器中獲取 auth 用戶的 id,所以我想建議,

 Route::get('/profile/{id?}', 'ProfileController@profile');

public function profile(Request $request, $id = NULL){
   $id = !empty($id) ? $id : Auth::user()->id;
  $User = User::with(['complains'])->find($id);
  if(!$User) return abort(404, 'User with id:'.$id.' not found');

  return view('user.profile')->with(['user' => $User, 'complains' => $User-
  >complains]);
}

我希望這會奏效

粘貼到您的 homeController 中

public function index()
{
    return Redirect::to('profile/' .auth()->user()->id);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM