I'm trying to create a user while adding data to a second table via one form:
users table:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
info table:
Schema::create('infos', function (Blueprint $table) {
$table->id();
$table->string('fname');
$table->string('lname');
$table->string('dateofbirth');
$table->string('phonenumber')
$table->timestamps();
});
info_user table:
Schema::create('info_user', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('info_id');
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('info_id')->references('id')->on('infos')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
User.php Model
public function infos() {
return $this->belongsToMany(Info::class)->withTimestamps();;
}
Info.php Model
public function users() {
return $this->belongsToMany(User::class)->withTimestamps();
}
And my attempt at InfoController
public function store(Info $info, User $user, Request $request)
{
User::create([
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$data = new Info;
$data->fname = $request->fname;
$data->lname = $request->lname;
$data->dateofbirth = $request->dateofbirth;
$data->phonenumber = $request->phonenumber;
$data->save();
return redirect('/');
}
I'm trying to figure out how to register a user while adding info to the second table so they have a common info_user
table.
I think I succeeded, but only if it is right and especially safe.
public function store(Info $info, User $user, Request $request)
{
$user = User::create([
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$data = new Loan;
$data->fname = $request->fname;
$data->lname = $request->lname;
$data->dateofbirth = $request->dateofbirth;
$data->phonenumber = $request->phonenumber;
$data->save();
$user->infos()->attach($data);
return redirect('/');
}