【问题标题】:Redirect to profile page after authentication in laravel在laravel中进行身份验证后重定向到个人资料页面
【发布时间】:2017-04-20 12:23:39
【问题描述】:

当用户登录时,我希望他们被重定向到他们的个人资料页面而不是主页。我在另一个控制器中有一个获取用户配置文件的方法。不知道我需要做什么,因为用户配置文件需要一个用户名变量,但是当用户登录时,我只要求输入电子邮件和密码。

我的路由文件,但是下面的方法与认证控制器在不同的控制器中。

Route::get('/user/{username}', [
    'uses' => 'ProfileController@getProfile',
    'as' => 'profile.index',
    'middleware' => ['auth'],
    ]);

我的以下方法在我的身份验证控制器中。

public function postSignin(Request $request)
{
    $this->validate($request, [
        'email' => 'required',
        'password' => 'required',

        ]);

    if (!Auth::attempt($request->only(['email', 'password']),      $request->has('remember'))) {
        return redirect()->back()->with('info' , 'Could not sign you in with that info.');
    }

        $user= User::where('username', $username)->first();
        return redirect()->route('profile.index')
        ->with('info', 'You are now signed in.')
        ->with('user', $user);
     }

以下内容在我的个人资料控制器中..

public function getProfile($username)
{
    $user= User::where('username', $username)->first();

    if (!$user){
        abort(404);
    }
    return view('profile.index')
        ->with('user', $user);
}

【问题讨论】:

    标签: laravel-5.2


    【解决方案1】:

    要正确构建路由,您需要在此处传递用户名:

    $user = User::where('username', $username)->first();
        return redirect()->route('profile.index', ['username' => $user->username])
        ->with('info', 'You are now signed in.')
        ->with('user', $user);
    

    【讨论】:

    • 我试过了,但我得到用户名未定义。当我只传递电子邮件和密码时,我不知道该怎么做
    • 这只是一个例子,伙计,我不知道你的数据库结构,但你应该知道,事实是你需要将一些东西传递给那个路由才能正确构建它
    • 是的,在我的数据库中,我的用户名字段是“用户名”,但我得到...缺少 [Route: profile.index] [URI: user/{username}] 所需的参数。
    【解决方案2】:

    从提供的电子邮件中获取用户名并将$username 变量传递给路由:

    public function postSignin(Request $request)
    { 
          if (!Auth::attempt($request->only(['email', 'password']),$request->has('remember'))) 
          {
               return redirect()->back()->with('info' , 'Could not sign you in with that info.');
          }
    
       $username=User::where(['email'=>$request->email])->first()->username;
       return redirect()->route('profile.index')->with('username', $username);
    }
    

    【讨论】:

    • 当我尝试时出现错误:缺少 [Route: profile.index] [URI: user/{username}] 所需的参数。
    • @Slillz return redirect('user/{$username}');
    • 他们给了我:Application.php 第 902 行中的 NotFoundHttpException:
    【解决方案3】:

    你可以像下面这样使用。

      if (!Auth::attempt($request->only(['email', 'password']),      $request->has('remember'))) {
        return redirect('profile.index')->with('info' , 'Could not sign you in with that info.');
    

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 2019-06-06
      • 2016-07-25
      • 2020-09-05
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多