繁体   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