x69 x69 - 2 years ago 110
PHP Question

Laravel - php How to get current Id while inserting value in Database?

I want to get the current ID while inserting the value in database.Which i will use to save custom Data. How Do I do it?

I have written a query already.

$currentId = Student::orderBy('id', 'desc')->get(['id']) + 1;

But it's showing the following Error :

Object of class Illuminate\Database\Eloquent\Collection could not be
converted to int

Answer Source
$currentId = Student::orderBy('id', 'desc')->first()->id + 1;

But on the heavy traffic website this potentially can cause problems with data integrity, so I'd user this approach:

$student = new Student();
$currentId = $student->id;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download