Maybe someone will notice that I'm asking this question again but I have reason for that. I have asked two questions before about this problem and I didn't find any good еxplanation and answer..
How to make two types of users in Laravel
Register new type of user in Laravel 5.3
I will try to explain better now what is my question in general. I'm trying to register two types of users, and my idea is to have two different tables for that users, and the second problem that I have is how to make multi authentication after I register the user on one same login form
.
I'm searching for answers for long time and I didn't find any good answer.
Thank you very much!
You have to override the built-in authentication function in Laravel.
NOTE: For laravel 5.3 : the functions are in RegisterController.php
and you have to php artisan make:auth
to create these controllers (refer to https://laravel.com/docs/5.3/authentication).
NOTE: For laravel 5.2 and lower :
When you look at your AuthController.php
, you will see it uses the trait AuthenticatesAndRegistersUsers
. Try to look at all the functions in this trait in Laravel's vendor php files (...\Illuminate\Foundation\Auth...) and you can re-use (override) them in your AuthController.php
by applying your desired changes to them.
In your case, you probably want to change 3 functions register
,validator
and create
. So find these functions in the authentication controller and add your custom code.
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
//Add custom code here
$new_user = $this->create($request->all());
//Add custom code here
Auth::guard($this->getGuard())->login($new_user);
return redirect($this->redirectPath());
}
//Here you can differentiate the columns for each type of users...
protected function create(array $data)
{
if ($data['user_type']=='Type1'){
return UserType1::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'customInfoType1' => 'this is specific to User Type 1'
]);
}else{
return UserType2::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'customInfoType2' => 'this is specific to User Type 2'
]);
}
}
//And don't forget to change the validator if the validation rules are different for each type
protected function validator(array $data)
{
if ($data['user_type']=='Type1'){
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users_type1',
'password' => 'required|min:6',
'customInfoType1' => 'whatever validation rules'
]);
}else{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users_type2',
'password' => 'required|min:6',
'customInfoType2' => 'whatever validation rules'
]);
}
}