nameless
nameless

Reputation: 1521

Laravel get id of latest inserted user

I'm using the Laravel Auth to make users able to register. What I'm now trying is: After users register (if they have a special role selected), there is another row inserted into another table (then users) which holds the relating user id. This is the code for it:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use App\Complaint;


class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'username' => 'required|unique:users',
            'role' => 'required'
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {

        $user = new User;
        $user->name = $data['name'];
        $user->email = $data['email'];
        $user->username = $data['username'];
        $user->password = bcrypt($data['password']);
        $user->role = $data['role'];
        $user->templateURL = "";

        /*$user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'username' => $data['username'],
            'password' => bcrypt($data['password']),
            'role' => $data['role'],
            'templateURL' => ""
        ]);*/

        $user->save();


        if($data['role'] == 'Verkäufer'){
            $complaintRow = Complaint::create([
               'user_id' => $user->id,
                'complaintCount' => 0
            ]);
        }


        switch($data['role']){
            case 'Käufer':
                $user->attachRole(2);
                break;
            case 'Verkäufer':
                $user->attachRole(3);
                break;
            default:
                $user->attachRole(2);
                break;
        }


        return $user;
    }
}

But it's not working correctly, the user is inserted as well as a row for the complaints, but somehow $user->id seems to be null, the column always has user_id set to 0. Any ideas why this could be like this?

EDIT: I got it working now... It was actually not the code I posted, I just didn't make the user_id field fillable in the complaint table, that's why there was 0 in always, because 0 was the default value, so it just didn't set it.

Thanks all for the answers anyway.

Upvotes: 6

Views: 4708

Answers (6)

Binit Ghetiya
Binit Ghetiya

Reputation: 1979

You did all most correct you just need to change,

when you are saving user object it will return saved user object so just grab that object and use in furcher conditions.

$saved_user = $user->save();

if(!empty($saved_user)){
      if($data['role'] == 'Verkäufer')
        {
                    $complaintRow = Complaint::create([
                       'user_id' => $saved_user->id,
                        'complaintCount' => 0
                    ]);
                }
  } else {
     throw new error(500);

}

Hope this will help thanks :)

Upvotes: 0

Pankit Gami
Pankit Gami

Reputation: 2553

As per Laravel Eloquent ORM, $user->id will return the Id of user. If you are getting null, then there might be error in saving. (https://stackoverflow.com/a/21084888/6628079)

Try printing $user after saving it.

UPDATE: It would be better if you add data in complaint table if user is saved successfully.

protected function create(array $data)
{

    $user = new User;
    $user->name = $data['name'];
    $user->email = $data['email'];
    $user->username = $data['username'];
    $user->password = bcrypt($data['password']);
    $user->role = $data['role'];
    $user->templateURL = "";

    /*$user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'username' => $data['username'],
        'password' => bcrypt($data['password']),
        'role' => $data['role'],
        'templateURL' => ""
    ]);*/

    if ($user->save()) {
        if ($data['role'] == 'Verkäufer') {
            $complaintRow = Complaint::create([
                'user_id' => $user->id,
                'complaintCount' => 0
            ]);
        }


        switch ($data['role']) {
            case 'Käufer':
                $user->attachRole(2);
                break;
            case 'Verkäufer':
                $user->attachRole(3);
                break;
            default:
                $user->attachRole(2);
                break;
        }


        return $user;
    } else {
        // Your code if user doesn't save successfully.
    }
}

Upvotes: 2

ATIKON
ATIKON

Reputation: 447

Is column id exists? Try to set $primaryKey = 'id' on model (user).

After $user->save you can access to id like $user->id Or after $user->save try to get max id from your table.

$user = User::select('id')->max('id')->first();

Upvotes: 1

Imran
Imran

Reputation: 4750

This is because, Eloquent save method bool but not the instance of newly created Entity. For confirmation checkout this link: https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html

So, if you want to get the newly created instance you can either user create method or make another query to get newly inserted instance. First one is better ans easy. Here is how you can do it:

$user = User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'username' => $data['username'],
    'password' => bcrypt($data['password']),
    'role' => $data['role'],
    'templateURL' => ""
]);

Now, you have $user variable containing User instance. But to do this you need to consider fillable/guared issue in your model. I mean, in your model you have to add the following line:

protected $fillabe = ['name', 'email', 'username', 'password', 'role', 'templateURL']

Upvotes: 2

Alexey Mezenin
Alexey Mezenin

Reputation: 163938

$user->id will tell you created user's ID right after using save() method.

Upvotes: 0

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26278

Try this:

$lastId = User::create($userData)->id;

Upvotes: 0

Related Questions