dontHaveName
dontHaveName

Reputation: 1937

laravel inserting into multiple tables

I have 2 tables

#something - id, name, url
#something_users - id, id_something, email, password

My models

class Something extends Eloquent
{

    protected $table = 'something';

    protected $fillable = ['name', 'email', 'password'];

    public $errors;


    public function User()
    {
        return $this->belongsTo('User', 'id', 'id_something');
    }
}

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;


    protected $table = 'something_users';

    protected $hidden = array('password', 'remember_token');

    public function Something()
    {
        return $this->belongsTo('Something');
    }

}

Controller

$input = Input::all();

// also some validation
$this->db->fill($input);

$this->db->password = Hash::make(Input::get('password'));

$this->db->push();

$this->db->save();

SQL

insert into `something` (`name`, `email`, `password`) values...

I need to insert name into the first table(something) and email, password into second(something_users)

How to do that? I have on clue about that.

Upvotes: 1

Views: 59775

Answers (2)

Anonymouse
Anonymouse

Reputation: 1

Laravel 6.

I want to add data to users table and customer table using one controller that is RegisterController.

<?php

 namespace App\Http\Controllers\Auth;

 use App\User;
 use App\Customer;
 use App\Http\Controllers\Controller;
 use App\Providers\RouteServiceProvider;
 use Illuminate\Foundation\Auth\RegistersUsers;
 use Illuminate\Support\Facades\Hash;
 use Illuminate\Support\Facades\Validator;

 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 registration.
 *
 * @var string
 */
protected $redirectTo = RouteServiceProvider::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, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */

//this part is my code
protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'role' => '2',
    ]);

    $customer = Customer::create([
        'user_id' => $user['id'],
        'firstname' => $data['name'],
        'lastname' => $data['name'],
        'email' => $data['email'],
        'address' => '',
        'phone' => '',
        'gender' => '',
    ]);

    return $user;
     }
 }

enter image description here

enter image description here

This answer is not the best one, because this answer is just a shortcut code so that my code is not error. maybe another error will appear in the future. but I hope my answer can solve your problem

Upvotes: 0

user1669496
user1669496

Reputation: 33118

Your relationships are a little screwed up, you probably want to change those. Note the hasMany() vs the belongsTo(). If a something can only have one user, you may wish to change the function to hasOne() from hasMany() and the name of the function to user() only because it makes more sense that way.

class Something extends Eloquent {

    protected $table = 'something';

    public function users()
    {
        return $this->hasMany('User', 'id_something');
    }
}

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    protected $table = 'something_users';

    protected $hidden = array('password', 'remember_token');

    public function something()
    {
        return $this->belongsTo('Something', 'id_something');
    }
}

And then to save a something and a user and have them linked, it's pretty easy.

$something = new Something;
$something->name = Input::get('name');
$something->url = Input::get('url');
$something->save();

$user = new User;
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));

$something->users()->save($user);

I'm not seeing your constructor so I don't know which model $this->db refers to, but you may want to replace the somethings or users depending on what you have. To keep your dependency injection going, I'd suggest naming your dependencies what they actually are.

class SomeController extends BaseController {

    public function __construct(User $user, Something $something)
    {
        $this->user = $user;
        $this->something = $something;
    }

    public function someFunction()
    {
        $this->something->name = Input::get('name');
        $this->something->url = Input::get('url');
        $this->something->save();

        $this->user->email = Input::get('email');
        $this->user->password = Hash::make(Input::get('password'));
        $this->something->users()->save($this->user);
    }
}

Upvotes: 15

Related Questions