skip to Main Content

On laravel site making Http Post request I need to get id of the l;ast inserted ID, like:

$response = Http::withToken($this->token)->post(route('articles.store'), [
    'title'        => 'Item Title lorem',
    'text'         => 'Item Text lorem',
    'text_shortly' => 'Item Text shortly lorem',
    'published'    => true,
]);

$lastItemId = DB::getPdo()->lastInsertId(); // this value is 0

New value is added and I see sql insert statement in sql logs, but $lastItemId is zero…

Can I to get this value somehow ?

"laravel/framework": "^9.19",
"guzzlehttp/guzzle": "^7.2",

Thanks in advance!

2

Answers


  1. To get lastInsertId, you need some altering to be done.


    In the Store function

    $article = Article::create([
        'title' => $request->input('title'),
        # your fields
    ]);
    
    return response()->json(['id' => $article->id]);  # importent part
    

    In the HTTP Client

    $lastItemId = $response->json()['id'];
    
    Login or Signup to reply.
  2. you can select id from the last row

    Article::select('id')->latest();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search