-1

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!

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
Petro Gromovo
  • 1,755
  • 5
  • 33
  • 91
  • 1
    This: `DB::getPdo()` is wrong, the lastInsertId() is already on the DB object – UnderDog Dec 24 '22 at 06:53
  • 2
    Why are you doing a POST request to your own site? That is generally bad practice. Usually you'd extract the controller code to a separate utility library and call that from both the controller and this code, that way you can control what to return. Sidenote: Because you are doing this your site is creating a new database connection and the last insert ID is on that connection not the one that is making the request – apokryfos Dec 24 '22 at 08:32

2 Answers2

2

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'];
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
0

you can select id from the last row

Article::select('id')->latest();