I've never used Laravel before and I'm working on a 3 part registration using laravels default user registration & auth for step 1 of the form. Each step has its own table. The id column of step 1s table is used to link all 3 tables.
Currently im using $id = Auth::user()->id
to get the logged in users id in the step 2 controller. Instead how can I route/pass the id after the user is created to step 2 controllers store method and redirect the view to step 2?
in authcontroller
protected function create(array $data)
{
return User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
'firstName' => $data['firstName'],
'middleName' => $data['middleName'],
'lastName' => $data['lastName'],
]);
}
in Illuminate\Foundation\Auth\RegistersUsers;
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::guard($this->getGuard())->login($this->create($request->all()));
// pass id to store method in profile and redirect to profileinfo
return view('user/profileinfo');
}
}
You can change create method in AuthController in this way :
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$id= $user->id; // Get current user id
return $user;
}
Instead of using create()
method which returns true
or false
, you should use save()
method which returns the model:
$id = $data->save()->id;
But if you still need short syntax, you can use mass assignment:
$userModel = new User($data);
$userModel->save();
$id = $userModel->id;
Try this approach:
$data = new FooModel(); // or in your case User();
$data->column_1 = 'value_1';
$data->column_2 = 'value_2';
$data->save();
and now after calling save()
, $data->id
should give you last inserted ID, so that you can use it wherever you want.
Just keep in mind, that if the PK column (the one with ID) is not auto-increment, it will always return 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With