9
votes

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');
}

}
4
What is the problem with using $id = Auth::user()->id ? - Abhishek
@Abhishek Because in each controller than I will have to have a getId function that makes sure each user is logged in and returns the id. I was thinking that its better to pass id as a parameter to the store method in each controller - noname

4 Answers

8
votes

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;
}
3
votes

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.

3
votes

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;
0
votes

You can change your create() function to

protected function create(array $data)
{
  $user = new User();
  $user->email = $data['email'];
  $user->password = bcrypt($data['password']),
  $user->firstName = $data['firstName'],
  $user->middleName = $data['middleName'],
  $user->lastName = $data['lastName'];
  $user->save();

  return $user->id;
 }