Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 - How to get id of newly created user and pass it to a controller

Tags:

laravel

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

}
like image 589
noname Avatar asked May 12 '16 03:05

noname


3 Answers

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;
}
like image 68
allaghi Avatar answered Oct 19 '22 19:10

allaghi


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;
like image 42
Alexey Mezenin Avatar answered Oct 19 '22 19:10

Alexey Mezenin


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.

like image 20
Matt Komarnicki Avatar answered Oct 19 '22 20:10

Matt Komarnicki