Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Get the ID of User::create and insert new row using that ID

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?

like image 621
TheGod39 Avatar asked May 06 '16 14:05

TheGod39


People also ask

How can I get ID after insert in laravel?

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.

How do I create a new row in laravel?

You can create a new row as simple as User::create(Input::all()) when your $fillable is properly set in the model.

What is :: In laravel?

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.


3 Answers

Try to use ->id of returned object, something like:

$id = $this->create($data)->id; 
like image 156
Alexey Mezenin Avatar answered Sep 23 '22 08:09

Alexey Mezenin


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, ]); 
like image 34
Pawel Bieszczad Avatar answered Sep 22 '22 08:09

Pawel Bieszczad


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;
like image 30
Md Shohag Avatar answered Sep 22 '22 08:09

Md Shohag