x69 x69 - 5 months ago 14x
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

$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;