记录用户的会话返回undefined

时间:2017-07-24 12:04:01

标签: laravel laravel-5

我在Laravel 5.4中有自定义登录功能,这似乎有效但不完全正确。我在UserController.php中的内容是

public function loginSubmit() 
{
    $user = User::where('username', Input::get('username'))->first();
    if (!$user) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    if (!Hash::check(Input::get('password'), $user->password)) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user->last_login = \Carbon\Carbon::now();
    $user->save();
    Session::put('user', ['user_id' => $user->user_id]);
    //dd(Session::get('user', null));   

    return Redirect::to('/');
}

dd(Session::get('user', null));返回

array:1 [▼
  "user_id" => 1
]

这意味着ID = 1的用户被记录并存储在会话中。在共享用户会话的BaseController.php中我有这个

public static function isLoggedIn() 
{
    $user = Session::get('user', null);
    if ($user !== null) {
        return true;
    } else {
        return false;
    }
}

但是当我试图显示登录用户的用户名时

{{ $user->username }}

我有错误

  

未定义的变量:user

这是我的用户模型

namespace App;

use Illuminate\Database\Eloquent\Model;
use Eloquent; 
use DB;

use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract 
{

    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password');
    protected $primaryKey = 'user_id';
}

知道我的会话有什么问题吗?

1 个答案:

答案 0 :(得分:0)

这表示您正在使用的刀片文件中未定义$user

以用户作为参数调用视图(我认为这是最好的方法):

$user = Session::get('user', null);
return view('yourview')->with(['user' => $user];

或使用刀片文件中的会话:

{{ Session::get('user', null)->username }}

编辑:使用View::share。您可以将其放在服务提供商的boot功能中:

    class AppServiceProvider extends ServiceProvider
    {
        /**
         * Bootstrap any application services.
         *
         * @return void
         */
        public function boot()
        {
            $user = Session::get('user', null);
            View::share('user', $user);
        }
        //...
    }
相关问题