How to use authentication on custom model in Larav

2019-04-12 16:07发布

问题:

I'm making new custom model for user in laravel. I'm using the default User laravel model for one type of users that I will have, and new Merchant model for other type of users.

I make select option in the register view for chosing which type of user will be registered for better control in the controller.

<select id="user_type" name="user_type">
  <option value="user">User</option>
  <option value="merchant">Merchant</option>
</select>

This is my modified the default RegisterController for both type of users:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Merchant;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/index';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    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());
    }

    protected function validator(array $data)
    {
        if($data['user_type']=='user'){
            return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'user_type' =>'required'
        ]);
        }else{
            return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'user_type' =>'required'
           ]);
        }
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        if($data['user_type']=='user'){
            return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
        ]);
       }else{
           return Merchant::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
        ]);
       }

    }

}

To mention that register function is not by default in register controller, so I put that function because I already view that solution How to register more than one type of users and how to make multi auth in laravel 5.3 but I don't know how to modify that.

But the problem now is with the authentication after I submit the registration form. If I register new user it's working fine, but if I register merchant it saved the user in database and after that it doesn't log in the merchant if it doesn't exist any user in the users table. But if it already exist any user in the users after I register the merchant it log in the last user which is created in users table.

So my question is how to modify the authentication for merchant user.

Thank you!

UPDATE:

Register function

public function register(Request $request)
    {
         if($request->user_type =='user'){
                $auth = auth()->guard();
            } else{
                $auth = auth()->guard('merchant');
            }

            $user = $this->create($request->all());
            auth()->login($user);

            return redirect($this->redirectPath());


    }

回答1:

  1. Go to /config/auth.php
  2. Find guards element of an array

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
    
  3. Add a guard merchant to this array with provider value of merchants

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    
        'merchant' => [
            'driver' => 'session',
            'provider' => 'merchants',
        ],
    ],
    
  4. Now find providers element of this configuration

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
    ],
    
  5. Add merchants provider with model value of your Merchant model

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
    
        'merchants' => [
            'driver' => 'eloquent',
            'model' => App\Merchant::class,
        ],
    ],
    
  6. Now you can simply authenticate normal users via guard('web') and merchant users via guard('merchant')

And for you register function

public function register(Request $request)
{
    $guard = $request->user_type == 'user' ? 'web' : 'merchant';
    $user  = $this->create($request->all());

    auth()->guard($guard)->login($user);

    return redirect($this->redirectPath());
}

You can use packages too...

For example there's an awesome package: https://github.com/Sarav-S/Laravel-Multiauth

It will help you to handle all that hard stuff.



回答2:

First You need to set new guard at auth.php. And when login using merchant change the guard method so Laravel will look into merchant instead of users.

    if($request->user_type =='user'){
        $auth = auth()->guard();
    } else{
        $auth = auth()->guard('merchant');
    }

    $auth()->login($user);

    return redirect($this->redirectPath());

https://laravel.com/docs/5.3/authentication