Laravel gets id of last inserted user

I use Laravel Auth so that users can register. What I'm trying to do now: After registering users (if they have a special role), there is another row inserted into another table (then users), which contains the associated 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 doesn’t work correctly, the user is inserted in the same way as the complaint line, but somehow $user->id seems to be null, the column always has user_id set to 0. Any ideas why this might look like this?

EDIT : I got it now ... Actually this is not the code I wrote, I just did not make the user_id field fillable in the complaint table, so it was always 0 because 0 was the default value, so it just didn't set it .

Thanks everyone for the answers anyway.

+5
source share
6 answers

According to the Laravel Eloquent ORM, $user->id will return the user $user->id . If you get zero, then there may be an error while saving. ( fooobar.com/questions/382866 / ... )

Try printing $user after saving.

UPDATE: It would be better if you added data to the complaint table if the user was successfully saved.

 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. } } 
+2
source

This is because Eloquent retains the bool method, but not an instance of the newly created object. To confirm, check this link: https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html

So, if you want to get a newly created instance, you can either create a custom method or make another request to get the newly inserted instance. The first is better and easier. Here's 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 the $user variable containing the User instance. But for this you need to consider the fillable / protected issue in your model. I mean, in your model, you should add the following line:

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

Is there an id column? Try setting $primaryKey = 'id' to the model (user).

After $user->save you can access the id as $user->id Or after $user->save try to get the maximum id from your table.

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

Try the following:

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

$user->id tells you that you created the user ID immediately after using the save() method.

0
source

You did everything right, you just need to change,

when you save a user object, it will return the saved user object , just to capture this object and use it in a mechanic's 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 helps thanks :)

0
source

Source: https://habr.com/ru/post/1260446/


All Articles