Register new type of user in Laravel 5.3

馋奶兔 提交于 2019-12-11 08:42:17

问题


I'm trying to make two types of users in laravel and I have two tables for that. I want to use defined register view and controller from laravel, but when I register new users it saved only in the first table.

The problem is with this url('/register') from here <form class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}" id="form_reg1">which I don't know how to edit this url for sending post request, because I'm using two forms, one for the first type of user, and one for the second type of user.

This is the first controller:

<?php

namespace App\Http\Controllers\Auth;

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

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
     */
    protected function validator(array $data)
    {
        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',
        ]);
    }

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

and this is second controller:

<?php

namespace App\Http\Controllers\Auth;

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

class RegisterMerchantController 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
     */
    protected function validator(array $data)
    {
        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',
        ]);
    }

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

So any idea?


回答1:


There are a few ways to approach this problem. One of them is to use a user type hidden field in the register.blade.php and based on the field to have login in your register controller to validate the input.

<input type="hidden" name="user_type" id="user_type" value="user">

You can use a select like

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

For example the RegisterController:

protected function validator(array $data)
{
    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|in:user,merchant'
    ]);
}

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



回答2:


It would be better if you save users into a same table and use polymorphic relationships to distinguish both of them. This technique will also help you to authenticate users as you can authenticate users by referencing to a single table (users).

So your table structures would be like this:

- users
    - id
    - owner_id
    - owner_type
    - email
    - password
    - token
    - ...

- clients
    - id
    - name
    - gender
    - mobile
    - ...

- merchants
    - id
    - name
    - gender
    - mobile
    - ...

Your Models - Client, User & Merchant would look like this:

class User extends Model
{
    public function owner()
    {
        return $this->morphTo();
    }
}

class Client extends Model
{
    public function user()
    {
        return $this->morphOne(User::class, 'owner');
    }
}

class Merchant extends Model
{
    public function user()
    {
        return $this->morphOne(User::class, 'owner');
    }
}

Now inside your HTML form, you can add a select option to select the type of user you want to create (or you can take the help of hidden fields to implement it), I am using a select option for the demonstration purpose:

<form action="{{ route('register_route_name') }}" method="POST">
    {{ csrf_field() }}
    <select name="type">
        <option disabled> Select Type of User </option>
        <option value="1"> Client </option>
        <option value="2"> Merchant </option>
    </select>

    <input type="text" name="name">
    <input type="text" name="mobile">

    <input type="radio" name="gender" value="0"> Male
    <input type="radio" name="gender" value="1"> Female

    <input type="email" name="email">
    <input type="password" name="password">

    <input type="submit" value="Register">

</form>

Now inside your controller you'll add users according to the type you'll get from the for like this:

class RegisterController extends Controller
{

    public function register()
    {
        // You should use validator here to validate your inputs here...
        $inputs = request()->except('_token');

        if($inputs['type'] == 1) {
            $profile = Client::create(array_only($inputs, ['mobile, 'gender', 'name']));
        } else {
            $profile = Merchant::create(array_only($inputs, ['mobile, 'gender', 'name']));
        }

        $user_inputs_arr = array_only($inputs, ['email', 'password']);
        $user_inputs_arr['password'] = bcrypt($inputs['password']);

        $user = $profile->user()->create($user_inputs_arr);
        // Hence your client is registered successfully...
    }

}

Hope this helps!



来源:https://stackoverflow.com/questions/40974275/register-new-type-of-user-in-laravel-5-3

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