x69 x69 - 7 months ago 17
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
$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();
....
$student->save();
$currentId = $student->id;
Comments