Wednesday 1 May 2019

Laravel 5.8 - Get Last Inserted ID



If you know how to get last inserted id in Laravel. If you not know then this post will help you to know how can we get last inserted record id in Laravel. Because in this post we have share Laravel tutorial on getting last inserted data id by 4 different method. So, from this post you can learn 4 method by which you can get the value of last inserted id in Laravel. Here we have use Laravel 5.8 framework in which we have describe 4 method by which we can get the value of last inserted id. In Web application development by using Laravel there are many place where we need to get the value of last inserted id value. So, here we have describe 4 different way by which we can get the last inserted id. In place place of web application we want to get last id of inserted record in Laravel application. Below you can find complete step by step process for get last id in Laravel.



Step 1 - Install Laravel 5.8 framework


First we need to download latest version of Laravel, for this we have to write following command in command prompt. It will install latest version of Laravel in you computer.


composer create-project laravel/laravel=5.8 ajax-crud


Step 2 - Make Database Connection


First we need to make database connection, for this we have to open .env file and in that file we have to define mysql database configuration, which we can see below.


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Step 3 - Create Model


In this step we have to create model, because by using two method in which we need Laravel Eloquen model class. So we need to create model here. For this we have to go in command prompt and write follwing command. It will create LastId.php model file under app folder.


php artisan make:model LastId -m


After creating model file, in this we have to define table column name on which we have to do database operation. So, below you can find LastId.php model file.

app/LastId.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class LastId extends Model
{
    protected $fillable = [
     'first_name', 'last_name'
    ];
}


Above model command has also create database migration file under database/migrations folder. In this file we have to define table column name with data type, which we have add in table. Below you can find migration file code.


<?php

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

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

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


Now we want to migrate this table defination to mysql database, for this we have to go command prompt and write following command, it will make last_ids table under mysql database.


php artisan migrate


Step 4 - Create Controller


For handle http request we need to make controller in Laravel, for this we have to go command prompt and write following command. It will make LastIdController.php in app/Http/Controllers folder.


php artisan make:controller LastIdController


In this controller file we have make two method. Below you can find two method description.

index() - This is the root method of this controller. It have load sample_form.blade.php file in browser.
getid() - This method has received ajax request for get the last inserted id. Below you can find 4 different method in Laravel by which we can get the value of last inserted id.
Method 1 - insertGetId() - This method has use Laravel Database class for get the value of last inserted id. For this we need to add use DB; line code at the header of this controller. Below you can find sample code of this method, how it has inserted data into database and return value of last inserted id in Laravel.





          $data = array(
       'first_name'  => $request->first_name,
       'last_name'  => $request->last_name
      );

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

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


Method 2 - lastInsertId() - This is second method by which we can get last inserted id in Laravel. For use this method, first we need to insert data into table by using Laravel Database library, and then after we need to use Laravel Database library getPDO() method with lastInsertID() method and this method will return last inserted id.


$data = array(
       'first_name'  => $request->first_name,
       'last_name'  => $request->last_name
      );

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

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


Method 3 - create() - This is third method by which we can get last inserted id in Laravel. This is Laravel Eloquent modal class method which has return data in array of object. So, we can get result in array of object by using create() method, and from object we can get last inserted id. For use this method we need to add use App\LastId; this line of code at the header of controller.


$data = array(
       'first_name'  => $request->first_name,
       'last_name'  => $request->last_name
      );

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

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


Method 4 - save() - This is the 4th method by which we can get last inserted id in Laravel. This save() method is also Laravel Eloquent Modal class method. For use this method. We we need to create object of modal class and in that object we need to add form data as object. And last we have to use save() method. This method has return result in object of an array and from that object of array we can get value of last inserted id in Laravel.


$result = new LastId;
$result->first_name = $request->first_name;
$result->last_name = $request->last_name;
$result->save();

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


By using above 4 method we can get the value of last inserted id in Laravel. After geting value of last inserted id, it will be send to Ajax request in json format. Whole source code of controller you can find below.

app/Http/Controllers/LastIdController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;

use App\LastId;

class LastIdController extends Controller
{
    function index()
    {
     return view('sample_form');
    }

    function getid(Request $request)
    {
     if($request->ajax())
     {
      $data = array(
       'first_name'  => $request->first_name,
       'last_name'   => $request->last_name
      );

            //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 = LastId::create($data);*/

            //Method 4
      $result = new LastId;
      $result->first_name = $request->first_name;
      $result->last_name = $request->last_name;
      $result->save();

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



Step 5 - Create View File


Below you can find source code of sample_form.blade.php file. This file has been store under resources/views folder. In this file you can find HTML code for form and Ajax jQuery code for submit form data to server script.


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Get Last Inserted ID</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">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="sample_form">
      @CSRF
      <div class="form-group">
       <label>First Name</label>
       <input type="text" name="first_name" class="form-control" />
      </div>
      <div class="form-group">
       <label>Last Name</label>
       <input type="text" name="last_name" 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(){
 $('#sample_form').on('submit', function(event){

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


Step 6 - Set Route


In Laravel application we need to set route for controller method. For this we have to open routes/web.php file. In this file you have to write following code for set route.


<?php

Route::get('last-id', 'LastIdController@index');

Route::post('last-id/getid', 'LastIdController@getid')->name('last-id/getid');

?>


For learn laravel application, we have to go to command prompt and write following command.


php artisan serve


Above command will start laravel server and it will return base url of your laravel application. For run this last inseted id application we need to write following url.


http://127.0.0.1:8000/last-id




1 comment:

  1. amazing!! You could do with pure PHP PDO without framework

    ReplyDelete