Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 273
nameless Avatar asked Nov 28 '16 10:11

nameless


People also ask

How can I get last insert ID in laravel 6?

so, here we have find 4 diffrent way to get last inserted ID in laravel. you can use it and get last ID of inserted record in laravel application. DB::table('users')->insert([ 'name' => 'TestName' ]); $id = DB::getPdo()->lastInsertId();; dd($id); 3) Using create() method.

What are the difference between Insert () and InsertGetId () in laravel?

Insert(): This function is simply used to insert a record into the database. It not necessary that ID should be autoincremented. InsertGetId(): This function also inserts a record into the table, but it is used when the ID field is auto-increment.


3 Answers

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.
    }
}
like image 173
Pankit Gami Avatar answered Oct 21 '22 05:10

Pankit Gami


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']
like image 38
Imran Avatar answered Oct 21 '22 06:10

Imran


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();
like image 1
ATIKON Avatar answered Oct 21 '22 05:10

ATIKON