D
D
Denis Bukreev2017-09-29 22:58:26
Laravel
Denis Bukreev, 2017-09-29 22:58:26

How to get the id of a record inserted into the database using Eloquent in laravel?

I found how to get the id when inserting a record manually using DB::table('autos')->insertGetId()
For eloquent, I found related models in the docks - at first it seemed that this was what I needed, but no.
I need to shove a huge form into three tables, each of which depends on the next.
Those. first I insert a record, for example, into the autos table, then, having received the id of this record, I insert the data into the users table and here I use the received id
But how to get this id?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D3lphi, 2017-09-29
@denisbookreev

$auto = Auto::create([
    // ...
    'key1' => 'val1',
    'key2' => 'val2',
    // ...
]);

User::create([
    // ...
    'auto_id' => $auto->id, // Ох уж это магия... Создайте лучше геттер.
    // ...
]);

Or
$id= Auto::insertGetId([
    // ...
    'key1' => 'val1',
    'key2' => 'val2',
    // ...
]);

User::insert([
    // ...
    'auto_id' => $id,
    // ...
]);

You can link "models" with relationships and do this:
$user->auto()->attach($auto);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question