Can I create a new class that inherits from User in Laravel 5.2?

感情迁移 提交于 2019-12-03 07:40:37

Yes, you can extend the class Illuminate\Foundation\Auth\User:

use Illuminate\Foundation\Auth\User as Authenticatable;

class Researcher extends Authenticatable {
    //My class definition here.
}

If you take a look at User class:

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

you see that it extends the Model class and implements all the other useful interfaces for authentication handling

you can safely extend the User class, because Laravel is good enough to work with the Illuminate\Contracts\Auth\Authenticatable interface to handle the authentication and not directly with the User class

In fact if you check in:

Illuminate/Auth/SessionGuard.php

That is the main class for auth handling, you'll see that all the auth actions are made against the Illuminate\Contracts\Auth\Authenticatable interface, i.e:

/**
 * Log a user into the application.
 *
 * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
 * @param  bool  $remember
 * @return void
 */
public function login(AuthenticatableContract $user, $remember = false)
{
    //other code
} 

I Think that your real problem would be: how to instantiate the classes Researcher and Admin instead of the User class during the authentication process?

If you use Eloquent as authentication driver, by default Laravel is going to use the Illuminate\Auth\EloquentUserProvider to create an instance of the Model. So, if you want to create an instance one of your classes instead of User, you should override this provider (or create one of your own) and here you could choose which class to instantiate

I think the best way to work with this concept is with roles and keeping the User Class intact. See https://github.com/spatie/laravel-permission for details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!