程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Laravel 5 Can not get authenticated user from view

发布于2023-01-19 16:54     阅读(451)     评论(0)     点赞(16)     收藏(5)


I am trying to use laravel authentication service.

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)

 /**
     * 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):

  <?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. 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.


解决方案


Problem Solved:

The main problem is that my user table id is customized which is not a auto_increment id.

After adding 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. If we use customized user_id like i do.

 /**
     * 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. What i got is always 0. Therefore, a User instance with id 0 is stored in laravel. When i call Auth:user(), we will get null instead of the User instance.

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

After adding public $incrementing = false; to my user model. I can get my user instance correctly with id that i defined.

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

Hope this can be helpful.

Thanks everyone helped before.



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.phpheidong.com/blog/article/476836/cb067d95db2ce2617939/

来源:php黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

16 0
收藏该文
已收藏

评论内容:(最多支持255个字符)