Manas
Manas

Reputation: 3330

How to get the ID of the latest record just inserted?

I'm trying to insert data into 2 different tables with relationship .. for example student and hobby. so student->hasOne(hobby) and hobby->belongsTo(student).

I'm inserting all this info at one go ..in one form for your reference in doing something like this: one form submision to 2 controllers in laravel.

Now my question is how do I save the hobby with the same id as of student? If I was saving student first then another form to save hobby then I can easily get the student_id first then I can save the hobby with the user id.

Upvotes: 1

Views: 96

Answers (4)

phaberest
phaberest

Reputation: 3220

You can insert it using the relation without even care about the id.

$hobby = auth()->user()->hobby()->create([
    'hobby_column1' => 'bla bla bla',
    'hobby_column2' => 'bla bla bla',
]);

In the example I use auth()->user(), but it can be any instance of User class.

Check Laravel Docs to better understand what you can do with relations.

Clearly you'll be able to get the id in $hobby, simply using $hobby->id once created.

Upvotes: -1

hktang
hktang

Reputation: 1833

How about insertGetId()?

$studentId = DB::table('students')->insertGetId(
    ['name' => 'John']
);

Then you can use te ID for tasks that relate to other models:

DB::table('hobbies')->inset(
    ['student_id' => $studentId, 'hobby' => $hobby]
);

You can find more about queries here: https://laravel.com/docs/5.4/queries

Upvotes: 1

Manas
Manas

Reputation: 3330

thx for the answers guys ..i did it by getstudentid() method and passing the student id...after creating the student.

Upvotes: 0

EddyTheDove
EddyTheDove

Reputation: 13259

You can submit to one controller. Easier. Then do

$student = Student::create([
    'name' => $request->name,
    ...
]);

$hobby = Hobby::create([
    'student_id' => $student->id,
    'schedule' => $request->schedule,
    ...other data
]);

Upvotes: 1

Related Questions