Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hjortur17's avatar

Find the next id in the database

What is the best way to find the next id in the table? For example, a customer is creating a booking number 119 and I want to log it, how would I find that in the same method I'm storing the booking?

See example:

public function createBooking(Request $request)
    {
        $token = uniqid();
        $booking_ref = uniqid();

        $nextId = Booking::find /////// what do here?

        $booking = Booking::create([
            'carNumber' => $request->input('carNumber'),
            'carSize' => $request->input('carSize'),
            'carMake' => $request->input('carMake'),
            'carType' => $request->input('carType'),
            'carColor' => $request->input('carColor'),

            'name' => $request->input('name'),
            'socialId' => $request->input('socialId'),
            'email' => $request->input('email'),
            'phone' => $request->input('phone'),

            'dropOffDate' => $request->input('dropOffDate'),
            'dropOffTime' => $request->input('dropOffTime'),
            'pickUpDate' => $request->input('pickUpDate'),
            'pickUpTime' => $request->input('pickUpTime'),

            'flightNumber' => $request->input('flightNumber'),

            'numberOfDays' => $request->input('numberOfDays'),
            'priceForDays' => $request->input('priceForDays'),

            'paidPrice' => $request->input('paidPrice'),

            'step' => $request->input('step'),

            'reservation_date' => date("Y-m-d H:i:s"),
            'token_expaire_date' => date("Y-m-d H:i:s"),

            'token_korta' => $token,
            'booking_ref' => $booking_ref
        ]);

        $booking->services()->attach($request->input('selectedServicesId'));

        $key = $booking_ref . '-' . $token;

        $dateTimeNow = date("Y-m-d H:i:s");

        Log::channel('slack')->notice('Bókun hefur stofnuð. Kt: '.($booking->socialId).', Netfang: '.($booking->email).', Bókunarnr.: '.$key.', Dags.: '.$dateTimeNow.', Skref: 1');

        if (request()->wantsJson()) {
            return $key;
        }

        return $key;
    }
0 likes
1 reply
Snapey's avatar
Snapey
Best Answer
Level 122

Why? You create the booking

$booking = Booking::create([

now $booking->id contains what would have been the $nextId

Please or to participate in this conversation.