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

phayes0289's avatar

Getting the ID from the Record Just Inserted Into MYSQL

Given the following method in my controller, how can I get the ID from MYSQL of the newly created record?

 public function store(Request $request)
    {
        $formFields = $request->validate([
            'type' => ['required'],
            'title' => ['required'],
            'tags'  => ['nullable'],
            'scope'  => ['required'],
            'purpose'  => ['required'],
            'body'  => ['required'],
            'status'  => ['nullable'],
            'pub_date'  => ['date'],
            'exp_date'  => ['nullable']
            ]);

        if ($request->has('pub_date')) {
            $publishedDate = $request->date('pub_date');
            $publishedDate->setHour($request->input('pub_hour'));
            $publishedDate->setMinute($request->input('pub_minute'));

            $formFields['pub_date'] = $publishedDate;
        }
        if ($request->has('exp_date')) {
            $expirationDate = $request->date('pub_date');
            $expirationDate->setHour($request->input('pub_hour'));
            $expirationDate->setMinute($request->input('pub_minute'));

            $formFields['exp_date'] = $publishedDate;
        }

        $formFields['user_id'] = auth()->id();

        Knowledgebase::create($formFields);

        return view('knowledgebase.index');

}
0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

Just assign the result to a variable:

$knowledgeBase =  Knowledgebase::create($formFields);

Then get the ID from the instance:

$knowledgeBase->id

Please or to participate in this conversation.