将公司注册添加到SaaS应用程序Laravel

时间:2016-11-27 13:23:07

标签: php mysql laravel laravel-5.2

我是从codeigniter到laravel而且仍然相当新,所以请原谅我,如果这是显而易见的。我正在努力寻找一些看起来相当简单但却无法在网上找到任何信息的东西,但却找到了一些接近的软件包。

我在注册时添加了一个输入字段来捕获公司名称,一旦他们点击注册就应该将用户信息添加到用户表中,但也将company_name添加到公司表的company_name列。

公司表:

+----+----------------+----------------+--------------+
| ID |  company_name  |   created_at   |  updated_at  |
+----+----------------+----------------+--------------+

用户表:

+----+------------+------+-------+----------+----------------+------------+------------+
| ID | company_id | name | email | password | remember_token | created_at | updated_at |
+----+------------+------+-------+----------+----------------+------------+------------+

公司型号:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Companies extends Model
{
    //
    //
    protected $fillable = [
        'company_name',
    ];

}

用户模型:

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Authenticatable
{
    use EntrustUserTrait;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function Company()
    {
        return $this->hasMany('App\Companies');
    }
}

在我的AuthController中:

namespace App\Http\Controllers\Auth;

use App\User;
use App\Companies;
use Validator;
use App\Http\Controllers\Controller;
use App\Http\Controllers\CompanyController;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

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

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => ['logout', 'getLogout']]);
    }

    /**
     * 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, [
            'company_name' => 'required|min:5|unique:companies,company_name',
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {

        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
        $user->Company()->create(['company_name'=>$data['company_name']]);
        $user->attachRole(1); // parameter can be an Role object, array, or id
        return $user;
    }
}

最后这是我的register.blade.php

中的表格
<div class="register-box-body">
            <div class="register-box-body">
<p class="login-box-msg">Register a new membership</p>
<form action="{{ url('/auth/register') }}" method="post">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <div class="form-group has-feedback">
        <input type="text" class="form-control" placeholder="Company name" name="company_name" value="{{ old('company_name') }}"/>
        <span class="glyphicon glyphicon-globe form-control-feedback"></span>
    </div>
    <div class="form-group has-feedback">
        <input type="text" class="form-control" placeholder="Full name" name="name" value="{{ old('name') }}"/>
        <span class="glyphicon glyphicon-user form-control-feedback"></span>
    </div>
    <div class="form-group has-feedback">
        <input type="email" class="form-control" placeholder="Email" name="email" value="{{ old('email') }}"/>
        <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
    </div>
    <div class="form-group has-feedback">
        <input type="password" class="form-control" placeholder="Password" name="password"/>
        <span class="glyphicon glyphicon-lock form-control-feedback"></span>
    </div>
    <div class="form-group has-feedback">
        <input type="password" class="form-control" placeholder="Retype password" name="password_confirmation"/>
        <span class="glyphicon glyphicon-log-in form-control-feedback"></span>
    </div>
    <div class="row">
        <div class="col-xs-8">
            <div class="checkbox icheck">
                <label>
                    <input type="checkbox"> I agree to the <a href="#">terms</a>
                </label>
            </div>
        </div><!-- /.col -->
        <div class="col-xs-4">
            <button type="submit" class="btn btn-primary btn-block btn-flat">Register</button>
        </div><!-- /.col -->
    </div>
</form>

这一切似乎都基于this question's answer。但是,当我注册它时,只需在users表中创建用户信息,其中company_id0,并且不会向companies表添加任何内容。

如何在注册时添加创建字段以便用户输入company_name,然后在保存时添加到companies表并将company_id存储在users表?

------------------------------------------- 更新 -------------------------------------------

这是我最新的Auth / RegisterController.php(我想最新版本的Laravel Framework版本5.3.24在各种控制器中打破了Auth up)

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Company;
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 = '/home';

    /**
     * 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, [
            'company_name' => 'required|unique:companies,company_name',
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        $company = \App\Company::create(['company_name'=>$data['company_name']]);

        $company->users()->create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);

        return $company;

        // User::create([
        //     'name' => $data['name'],
        //     'email' => $data['email'],
        //     'password' => bcrypt($data['password']),
        // ]);
    }
}

2 个答案:

答案 0 :(得分:4)

我现在看到了。你是在错误的方向做的。你必须先成为公司。然后一个用户。像这样:

   $company = \App\Companies::create(['company_name'=>$data['company_name']]);
   $company->users()->create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);

如果你考虑一下,这是有道理的。如果先创建用户,则无法填充company_id,因为公司尚不存在。

我强烈建议的一件事是以单数命名您的模型 - 公司而非公司,因为这是常见的惯例。

另外,请确保在公司模型上定义了users()方法

public function users()
    {
        return $this->hasMany(\App\User::class);
    }

这种方法是复数,因为一家公司可以有很多用户。它不是必需的,但更有意义。

此外,用户模型(您的方法Company())的关系应为:

public function company()
    {
        return $this->belongsTo(\App\Company::class);
    }

首先,惯例是编写以小写字母(camelCase)开头的方法名称。其次,您的用户模型已定义hasMany关系 - 这是错误的。用户没有很多公司,但他属于公司。

如果出于任何原因您想先创建用户,那么方法是创建用户,创建公司然后获取公司的ID并更新用户。

这样的事情:

$user = \App\Users::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
$company = \App\Companies::create(['company_name'=>$data['company_name']]);
$user->company_id = $company->id;
$user->save();

--------------基于问题更新的更新----------------

确保在create()方法上返回$ user,而不是$ company,因为它希望返回用户。

$company = \App\Companies::create(['company_name'=>$data['company_name']]);
$user = $company->users()->create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => bcrypt($data['password']),
            ]);
return $user;

答案 1 :(得分:1)

尝试制作&#39; company_id&#39;可在您的用户模型中填写。创建方法具有质量分配保护。您无法插入$ fillable数组中未列出的数据。