dimanche 31 janvier 2016

registration -> send data to two tables.

on registration i register a user to two tables - Users and Companies. Company.php and User.php have a relationship as you can see in code bellow.

in AuthController.php i use " 'user_id' => $user['id'], to pass id of new created row in users table to companies table. i know its somehow wrong but it works and i just want to know how could i create two rows at the same time with foreign key in much smarter way. i just think that i dont use that relationship properly though

company.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model {
    protected $fillable = [
        'ICO', 'user_id',
    ];
    public function user() {
        return $this->belongsTo('App\User');
    }
}

User.php

<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable {
    protected $fillable = [
        'firstname', 'middlename', 'lastname', 'email', 'password', 'usertype',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function company() {
        return $this->hasMany('App\Company');
    }
}

AuthController.php --> protected function create(array $data)

protected function create(array $data) {
        $user = User::create([
                    'firstname' => $data['firstname'],
                    'lastname' => $data['lastname'],
                    'middlename' => $data['middlename'],
                    'usertype' => $data['usertype'],
                    'email' => $data['email'],
                    'password' => bcrypt($data['password']),
        ]);
        $company = Company::create([
                    'ICO' => $data['ICO'],
                    'user_id' => $user['id'],
        ]);
        return $user;
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire