简体   繁体   English

Laravel 5无法从视图中获取经过身份验证的用户

[英]Laravel 5 Can not get authenticated user from view

I am trying to use laravel authentication service. 我正在尝试使用laravel身份验证服务。

The problem is I can successfully register a new user and redirect to the successful page. 问题是我可以成功注册新用户并重定向到成功页面。 Nevertheless, I can not get the authenticated user within the successful page. 但是,我无法在成功的页面内获得经过身份验证的用户。

Below is showing what have done so far. 下面显示了到目前为止所做的事情。

view 视图

    <form class="form-horizontal" role="form" method="POST" action="/auth/register">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">

    <div class="form-group">
        <label class="col-md-4 control-label">User Name</label>
        <div class="col-md-6">
            <input type="text" class="form-control" name="username" value="{{ old('first_name') }}">
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-4 control-label">E-Mail Address</label>
        <div class="col-md-6">
            <input type="email" class="form-control" name="email" value="{{ old('email') }}">
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-4 control-label">Password</label>
        <div class="col-md-6">
            <input type="password" class="form-control" name="password">
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-4 control-label">Confirm Password</label>
        <div class="col-md-6">
            <input type="password" class="form-control" name="password_confirmation">
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-6 col-md-offset-4">
            <button type="submit" class="btn btn-primary">
                Register
            </button>
        </div>
    </div>
</form>

User Model(register_info) 用户模型(register_info)

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['user_id','username', 'email', 'password','city'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'user_id';

Controller: 控制器:

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * When a user is successfully authenticated
     * they will be redirected to $redirectPath
     */
    protected $redirectPath = 'manybotest';

    /**
     * When a user is not successfully authenticated
     * they will be redirected to the $loginPath
     */
    protected $loginPath = '/login';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     *
     * 'email' => 'required|email|max:255|unique:register_info',
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'username' => 'required|max:255',
            'password' => 'required|confirmed|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {

        return User::create([
            'user_id' => uniqid('us'),
            'username' => $data['username'],
            'email' => $data['email'],
            'password' => bcrypt($data['password'])
        ]);
    }
}

Routes: 路线:

  Route::get('manybotest', function () {
        $users = Auth::user();
        return view('manybotest',compact('users'));
    });

Display view(manybotest.blade.php): 显示视图(manybotest.blade.php):

  <?php

        var_dump(Session::all());
        var_dump(Auth::check());
        var_dump(Auth::user());
        var_dump(Auth::id());
        var_dump($users);

    ?>

Result: 结果:

login_82e5d2c56bdd0811318f0cf078b78bfc => int 0//Session::all()
boolean false//Auth::check()
null//Auth::user()
int 0//Auth::id()
null//$users passed by routes

Question: 题:

I can get the user id from session. 我可以从会话中获取用户ID。 Why can't I get the authenticated user? 为什么无法获得经过身份验证的用户? I also try to inspect the inner code of laravel, the user was already set by laravel. 我还尝试检查laravel的内部代码,该用户已由laravel设置。

Problem Solved: 问题解决了:

The main problem is that my user table id is customized which is not a auto_increment id. 主要问题是我的用户表ID是自定义的,而不是auto_increment ID。

After adding public $incrementing = false ; 在添加public $ incrementing = false之后 to my user model. 对我的用户模型。 The problem solved. 问题解决了。

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;


    public $incrementing = false;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['user_id','username', 'email', 'password','city'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'user_id';

    /**
     * Get the bonding UserDetail
     *
     * @return UserDetail
     */
    public function getUserDetail()
    {
        return $this->hasOne('App\Model\UserDetail','user_id','user_id');
    }

}

Problem analysis: In laravel, by default the id of model user is set as auto-increment. 问题分析:在laravel中,默认情况下,模型用户的ID设置为自动递增。 If we use customized user_id like i do. 如果我们像我一样使用自定义的user_id。

 /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {

        return User::create([
            'user_id' => uniqid('us'),
            'username' => $data['username'],
            'email' => $data['email'],
            'password' => bcrypt($data['password'])
        ]);
    }

The returned model will contain a auto-increment id. 返回的模型将包含一个自动增量ID。 What i got is always 0. Therefore, a User instance with id 0 is stored in laravel. 我得到的总是0。因此,一个ID为0的User实例存储在laravel中。 When i call Auth:user(), we will get null instead of the User instance. 当我调用Auth:user()时,我们将获得null而不是User实例。

{"user_id":"0","username":"xxxxx@gmail.com","password":"xxxxxxx"}

After adding public $incrementing = false ; 在添加public $ incrementing = false之后 to my user model. 对我的用户模型。 I can get my user instance correctly with id that i defined. 我可以使用我定义的ID正确获取用户实例。

{"user_id":"us55f7e7afbe87f","username":"xxxxx@gmail.com","password":"xxxxxxx"}

Hope this can be helpful. 希望这会有所帮助。

Thanks everyone helped before. 谢谢大家的帮助。

You have to inject Guard and Register in to the constructor. 您必须将Guard注入并Register到构造函数中。

use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;

class AuthController extends Controller
{

    public function __construct(Guard $auth, Registrar $registrar)
    {
        parent::__construct();

        $this->auth = $auth;
        $this->registrar = $registrar;

        $this->middleware('guest', ['except' => 'getLogout']);
    }

If you look at AuthenticatesAndRegistersUsers , you can see that in the postRegister method, login is called on $this->auth . 如果查看AuthenticatesAndRegistersUsers ,则可以看到在postRegister方法中, login是在$this->auth上调用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM