A Form for two tables

0

Good afternoon, the question is this:

Bearing the model: Users = > Attributes: name, email, password User_profiles = > Attributes: last_name, city, phone, user_id

I need to add the last_name field in the registration form, and create a record in the user_profiles table user_id and last_name

I do not know if I should add to the User model to register the parameters of the user_profile model

What is the name of this action?

Thankful in advance for the answer.

Greetings.

    
asked by Rioyi Kaji 01.02.2018 в 20:41
source

1 answer

0

Why are you separating things in 2 different tables? You can leave everything in the same table

in the create user migration, put something like this:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('last_name');
        $table->string('email');
        $table->string('password');
        $table->string('ciudad');
        $table->string('telefono');
        $table->rememberToken();
        $table->timestamps();
    });
}

and in your User model

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

With that, when you do User :: create ($ request-> all ()) the user will be created and will include the extra data

on the other hand if you really want to separate the information, in the User model

Create a reaction

public function profile()
{
    return $this->hasOne('App\User_profiles');
}

When you save the information you will have to save it separately, like this:

$user = User::Create($request->all()); 
$profile = new User_profiles;
$profile->user_id = $user->id;
$profile->last_name = $request->get('last_name');
$profile->ciudad = $request->get('ciudad');
$profile->telefono = $request->get('telefono');
$profile->save(); 

then when you send a call to the user you can call their profile for the relationship

$user = User::find(1); //supongamos que devuelve el usuario con id 1
echo $user->name . " " .$user->profile->last_name;
    
answered by 02.02.2018 / 07:03
source