如何在 Laravel 中的自定义模型上使用身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40993143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:53:04  来源:igfitidea点击:

How to use authentication on custom model in Laravel

laravellaravel-5

提问by Devmasta

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

我正在为 laravel 中的用户制作新的自定义模型。我正在User为我将拥有的一种类型的用户使用默认的Laravel 模型,并Merchant为其他类型的用户使用新模型。

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

我在register视图中选择选项来选择将注册哪种类型的用户以更好地控制控制器。

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

This is my modified the default RegisterControllerfor both type of users:

这是我修改的RegisterController两种类型用户的默认值:

<?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 registerfunction 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.3but I don't know how to modify that.

提到该register功能不是默认的register controller,所以我把这个功能放在了,因为我已经查看了该解决方案如何注册不止一种类型的用户以及如何在laravel 5.3中进行多重身份验证,但我不知道如何修改它。

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

但是现在的问题是我提交注册表后的身份验证。如果我注册新的user它工作正常,但是如果我注册merchant它会将用户保存在数据库中,然后它不会登录商家,如果它userusers表中不存在。但是,如果在我注册它之后它已经存在user,则它会登录到表中创建的最后一个。usersmerchantuserusers

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());


    }

回答by Artur Subotkevi?

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

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

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

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
    ],
    
  5. Add merchantsprovider with modelvalue of your Merchantmodel

    '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')

  1. /config/auth.php
  2. 查找guards数组元素

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
    
  3. merchant向该数组添加一个provider值为merchants

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    
        'merchant' => [
            'driver' => 'session',
            'provider' => 'merchants',
        ],
    ],
    
  4. 现在找到providers这个配置的元素

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
    ],
    
  5. 添加merchants具有模型model价值的提供者Merchant

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
    
        'merchants' => [
            'driver' => 'eloquent',
            'model' => App\Merchant::class,
        ],
    ],
    
  6. 现在您可以简单地通过验证普通用户guard('web')和商家用户通过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

例如有一个很棒的包:https: //github.com/Sarav-S/Laravel-Multiauth

It will help you to handle all that hard stuff.

它将帮助您处理所有困难的事情。

回答by ssuhat

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

首先,您需要guardauth.php. 当使用merchant更改保护方法登录时,Laravel 将查看商家而不是用户。

    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

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