I have AuthController
in Laravel and I have 2 tables, one is Users
and one is Users_Information
and I want to insert into Users_Information
upon registration.
So I want to get the id from the following method and insert a new row and set the column ID of that row to the ID of the user I have just created.
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
protected function create(array $data)
{
return User::create([
'username' => $data['username'] . ' ' . $data['username2'],
'mail' => $data['mail'],
'password' => bcrypt($data['password']),
]);
}
I want to insert into Users_Information
with a column id
, current_food
and current_level
I have a controller for the Users_Information
called UserInformation
, would I just call UserInformation::create
but how would I get the id from the User::create
?
Using getPDO() Method You can also use the PDO Object to get the last inserted id of a table in Laravel. Firstly you will have to insert the record and right after that, you can call the lastInsertId() method on the PDO object.
You can create a new row as simple as User::create(Input::all()) when your $fillable is properly set in the model.
Basically its know as Scope resolution operator (::) Simply it is token which allow access to static, constant and overridden properties of method of a class. Example- in laravel we call model like this.
Try to use ->id
of returned object, something like:
$id = $this->create($data)->id;
The create()
method returns the model.
$user = User::create([ 'username' => $data['username'] . ' ' . $data['username2'], 'mail' => $data['mail'], 'password' => bcrypt($data['password']), ]); $userInfo = UserInformation::create([ 'user_id' => $user->id, 'current_food' => $food, 'current_level' => $level, ]);
Suppose, I have a model name Employee and I want to insert some data in this model also want to get table id. So I can achieve this easily by below code:
$employee = new Employee();
$employee->employeeName = 'Something';
$employee->save();
$employee->id;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With