Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert into multiple tables on user registration and edit the registration from

How would I insert rows in multiple tables (default User table and Parents table) when registering a new User? I know I need to edit Models, AuthController and view.

My User Model:

namespace Jcfk\Models\User;

class User extends Model implements AuthenticatableContract,
    CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'user';

    /**
     * @var string
     */
    protected $primaryKey = 'user_id';

    /**
     * @var bool
     */
    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    public function parents() {
        return $this->hasOne("app\Models\Parents");
    }

    /**
     * Is the current user an admin
     *
     * @return bool
     */
    public function isAdmin() {
        return $this->role_id === Role::ADMIN;
    }

    public function isParents() {
        return $this->role_id === Role::PARENT;
    }
}

Parents Model:

namespace Jcfk\Models\Parents;

class Parents extends Model
{
    protected $table = 'parent';
    public $timestamps = false;
    public $primaryKey = 'user_id';
    protected $fillable = ['name', 'phone', 'address', 'city_id', 'region',
        'postalcode'];

    public function user() {
        return $this->belongsTo("app\User");
    }
}

The Auth Controller:

namespace Jcfk\Http\Controllers\Auth;

use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Routing\Registrar;
use Jcfk\Models\User;
use Jcfk\Models\Parents;
use Validator;
use Jcfk\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct(Guard $auth, Registrar $registrar) {
        $this->auth = $auth;
        $this->registrar = $registrar;
        $this->middleware('guest', ['except' => '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, [
            //'name' => 'required|max:255',
            'email'    => 'required|email|max:255|unique:user',
            'password' => 'required|confirmed|min:6',
        ]);
    }

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

        $user = new User($data);
        $parents = new Parents($data);
        $user->save();
        $user->Parents()->save($parents);

    }
}

The database fields of Parents are user_id, name, phone, address, ...
The database fields of User are user_id, email, password, ...

I need help with my register.blade.php file as well

<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/register') }}">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">

    <div class="form-group">
        <label class="col-md-4 control-label">Name</label>

        <div class="col-md-6">
            <input type="text" class="form-control" name="name" value="{{ old('user_id') }}">
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-4 control-label">E-Mail Address</label>

        <div class="col-md-6">
            <input type="email" class="form-control" name="email" value="{{ old('email') }}">
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-4 control-label">Password</label>

        <div class="col-md-6">
            <input type="password" class="form-control" name="password">
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-4 control-label">Confirm Password</label>

        <div class="col-md-6">
            <input type="password" class="form-control" name="password_confirmation">
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-6 col-md-offset-4">
            <button type="submit" class="btn btn-primary">
                Register
            </button>
        </div>
    </div>
</form>
like image 683
Tonmoy Avatar asked Aug 10 '15 18:08

Tonmoy


1 Answers

Create a service or repository layer.

Create the repository:

<?php 

namespace App\Models\Repositories\User;

use App\Models\Entites\User;
use App\Models\Entites\Parent;

class UserRepository implements UserInterface
{
    public function create($input) 
    {
        $user = new User($data);
        $parents = new Parents($data);
        $user->save();
        $user->Parents()->save($parents);

        return $user;
    }
}

This implements an interface so we can map the interface to an implementation of it, so it can be injected:

<?php 

namespace App\Models\Repositories\User;

interface UserInterface
{
    public function create($input); 
}

Create a service provider, so it can be injected:

<?php 

namespace App\Models\Repositories\User;

use Illuminate\Support\ServiceProvider;

class UserRepositoryServiceProvider extends ServiceProvider 
{
    /**
     * Registers the UserInterface with Laravels IoC Container
     * @return void
     */
    public function register()
    {
        $this->app->bind('App\Models\Repositories\User\UserInterface', 'App\Models\Repositories\User\UserRepository');
    }
}

Add your provider to the config/app.php file:

    'providers' => [
        /*
         * Laravel Framework Service Providers...
         */

        /*
         * Your providers
         */
        App\Models\Repositories\User\UserRepositoryServiceProvider::class,
    ],

Now in your controller methods, you can do this:

use App\Models\Repositories\User\UserInterface;

protected function create(UserInterface $userRepository, array $data) {
    $userRepository->create($data);
}
like image 58
Chris Avatar answered Nov 12 '22 06:11

Chris