将公司注册添加到SaaS App Laravel



我来自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 IlluminateDatabaseEloquentModel;
class Companies extends Model
{
    //
    //
    protected $fillable = [
        'company_name',
    ];
}

用户模型:

namespace App;
use IlluminateFoundationAuthUser as Authenticatable;
use ZizacoEntrustTraitsEntrustUserTrait;
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('AppCompanies');
    }
}

和我的authcontroller:

namespace AppHttpControllersAuth;
use AppUser;
use AppCompanies;
use Validator;
use AppHttpControllersController;
use AppHttpControllersCompanyController;
use IlluminateFoundationAuthThrottlesLogins;
use IlluminateFoundationAuthAuthenticatesAndRegistersUsers;
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 IlluminateContractsValidationValidator
     */
    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>

这一切似乎是基于这个问题的答案。但是,当我注册时,只需在users表中创建用户信息,而company_id0,并且不会在companies表中添加任何内容。

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

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

这是我最新的auth/registercontroller.php(我猜最新版本的Laravel Framework版本5.3.24在各种控制器中打破auth)

<?php
namespace AppHttpControllersAuth;
use AppUser;
use AppCompany;
use Validator;
use AppHttpControllersController;
use IlluminateFoundationAuthRegistersUsers;
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 IlluminateContractsValidationValidator
     */
    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 = AppCompany::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']),
        // ]);
    }
}

我现在看到了。您在错误的方向上这样做。您必须先创建公司。然后是用户。这样的东西:

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

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

我强烈建议用单数字命名您的模型 - 公司而不是公司,因为这是常见的惯例。

另外,请确保您已经在公司模型上定义了用户()方法

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

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

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

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

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

如果您出于任何原因要首先创建用户,则该方法将是创建用户,创建公司,然后使用公司ID并更新用户。

类似的东西:

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

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

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

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

尝试在用户模型中填写'company_id'。创建方法具有大规模分配的保护。您无法插入未在$ folable数组中列出的数据。

相关内容

  • 没有找到相关文章

最新更新