Laravel 5.8 - Get Last Inserted ID With Example

Laravel 5.8 – Get Last Inserted ID With Example

Today, We want to share with you Laravel 5.8 – Get Last Inserted ID With Example.In this post we will show you laravel 5.8 get last insert id, hear for Laravel 5 Ways to Get Last Inserted Id we will give you demo and example for implement.In this post, we will learn about get last inserted id laravel query builder with an example.

Laravel 5.8 – Get Last Inserted ID With Example

There are the Following The simple About Laravel 5.8 – Get Last Inserted ID With Example Full Information With Example and source code.

  Dependent dropdown example in PHP MySQL

As I will cover this Post with live Working example to develop laravel get last inserted id after save, so the db::insert get id laravel for this example is following below.

Step 1 : Fresh Install Laravel 5.8 framework

install latest version of Laravel in you computer.

composer create-project laravel/laravel=5.8 laravel-webapp

Step 2 : Create a Database Connection

mysql database configuration

.env File

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=pakaifo
DB_USERNAME=product_catalog
[email protected]

Step 3 : Create Model

create FetchProductId.php model

php artisan make:model FetchProductId -m

app/FetchProductId.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class FetchProductId extends Model
{
    protected $fillable = [
     'product_title', 'product_desc'
    ];
}

database/migrations folder

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFetchProductIdsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products_001', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('product_title');
            $table->string('product_desc');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products_001');
    }
}

create a products_001 table under mysql database

php artisan migrate

Step 4 : Create Laravel 5.8 Controller

app/Http/Controllers/ProductController.php

php artisan make:controller ProductController

Method 1 : Get insertGetId()


   $data = array(
       'product_title'  => $request->product_title,
       'product_desc'  => $request->product_desc
      );

        $last_id = DB::table('products_001')
         ->insertGetId($data);

     return response()->json(['id' => $result->$last_id]);

Method 2 : lastInsertId() –

$data = array(
       'product_title'  => $request->product_title,
       'product_desc'  => $request->product_desc
      );

DB::table('products_001')->insert($data);
$last_id = DB::getPDO()->lastInsertId();

return response()->json(['id' => $last_id]);

Method 3 : create()

$data = array(
       'product_title'  => $request->product_title,
       'product_desc'  => $request->product_desc
      );

$result = FetchProductId::create($data);

return response()->json(['id' => $result->id]);

Method 4 : save()

$result = new FetchProductId;
$result->product_title = $request->product_title;
$result->product_desc = $request->product_desc;
$result->save();

return response()->json(['id' => $result->id]);

app/Http/Controllers/ProductController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;

use App\FetchProductId;

class ProductController extends Controller
{
    function index()
    {
     return view('create_product_frm');
    }

    function fetch_productid(Request $request)
    {
     if($request->ajax())
     {
      $data = array(
       'product_title'  => $request->product_title,
       'product_desc'   => $request->product_desc
      );

      //Method 1
      /*$last_id = DB::table('last_ids')
         ->insertGetId($data);*/

      //Method 2
      /*DB::table('last_ids')->insert($data);
      $last_id = DB::getPDO()->lastInsertId();*/

      //Method 3
      /*$result = FetchProductId::create($data);*/

      //Method 4
      $result = new FetchProductId;
      $result->product_title = $request->product_title;
      $result->product_desc = $request->product_desc;
      $result->save();

      return response()->json(['id' => $result->id]);
     }
    }
}

Step 5 : Create View File

resources/views/create_product_frm.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Get Last Inserted ID - pakainfo.com</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">pakainfo.com - Laravel 5.8 - Get Last Inserted ID</h3>
     <br />
     <div class="row">
      <div class="col-md-3">

      </div>
      <div class="col-md-6">
     <form method="post" id="create_product_frm">
      @CSRF
      <div class="form-group">
       <label>First Name</label>
       <input type="text" name="product_title" class="form-control" />
      </div>
      <div class="form-group">
       <label>Last Name</label>
       <input type="text" name="product_desc" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="submit" class="btn btn-info" value="Submit" />
      </div>
     </form>
     <div id="last_inserted_id"></div>
    </div>
    <div class="col-md-3">
    </div>
   </div>
  </div>
 </body>
</html>
<script>
$(document).ready(function(){
 $('#create_product_frm').on('submit', function(event){

  event.preventDefault();
  $.ajax({
   url:"{{ route('product-id/fetch_productid') }}",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   success:function(data){
    $('#create_product_frm')[0].reset();
    $('#last_inserted_id').html('Fetch Last Product Inserted ID - ' + data.id);
   }
  })
 });
});
</script>

Step 6 : Set Laravel 5.8 Route

routes/web.php

<?php

Route::get('product-id', '[email protected]');

Route::post('last-id/fetch_productid', '[email protected]_productid')->name('last-id/fetch_productid');

?>

Step 7: Laravel 5.8 Application Run

go to command prompt run This command

php artisan serve
http://127.0.0.1:8000/last-id

Angular 6 CRUD Operations Application Tutorials

Read :

  Bitcoin Altcoin Ethereum Cryptocurrency Exchange Script

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Laravel 5.8 – Get Last Inserted ID With Example.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Reply

avatar
  Subscribe  
Notify of