Get the Last Inserted Id Using Laravel Eloquent












209














I'm currently using the below code to insert data in a table:



<?php

public function saveDetailsCompany()
{
$post = Input::All();

$data = new Company;
$data->nombre = $post['name'];
$data->direccion = $post['address'];
$data->telefono = $post['phone'];
$data->email = $post['email'];
$data->giro = $post['type'];
$data->fecha_registro = date("Y-m-d H:i:s");
$data->fecha_modificacion = date("Y-m-d H:i:s");

if ($data->save()) {
return Response::json(array('success' => true), 200);
}
}


I want to return the last ID inserted but I don't know how to get it.



Kind regards!










share|improve this question





























    209














    I'm currently using the below code to insert data in a table:



    <?php

    public function saveDetailsCompany()
    {
    $post = Input::All();

    $data = new Company;
    $data->nombre = $post['name'];
    $data->direccion = $post['address'];
    $data->telefono = $post['phone'];
    $data->email = $post['email'];
    $data->giro = $post['type'];
    $data->fecha_registro = date("Y-m-d H:i:s");
    $data->fecha_modificacion = date("Y-m-d H:i:s");

    if ($data->save()) {
    return Response::json(array('success' => true), 200);
    }
    }


    I want to return the last ID inserted but I don't know how to get it.



    Kind regards!










    share|improve this question



























      209












      209








      209


      38





      I'm currently using the below code to insert data in a table:



      <?php

      public function saveDetailsCompany()
      {
      $post = Input::All();

      $data = new Company;
      $data->nombre = $post['name'];
      $data->direccion = $post['address'];
      $data->telefono = $post['phone'];
      $data->email = $post['email'];
      $data->giro = $post['type'];
      $data->fecha_registro = date("Y-m-d H:i:s");
      $data->fecha_modificacion = date("Y-m-d H:i:s");

      if ($data->save()) {
      return Response::json(array('success' => true), 200);
      }
      }


      I want to return the last ID inserted but I don't know how to get it.



      Kind regards!










      share|improve this question















      I'm currently using the below code to insert data in a table:



      <?php

      public function saveDetailsCompany()
      {
      $post = Input::All();

      $data = new Company;
      $data->nombre = $post['name'];
      $data->direccion = $post['address'];
      $data->telefono = $post['phone'];
      $data->email = $post['email'];
      $data->giro = $post['type'];
      $data->fecha_registro = date("Y-m-d H:i:s");
      $data->fecha_modificacion = date("Y-m-d H:i:s");

      if ($data->save()) {
      return Response::json(array('success' => true), 200);
      }
      }


      I want to return the last ID inserted but I don't know how to get it.



      Kind regards!







      php database laravel eloquent






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 at 7:08









      Blaze

      4,2621628




      4,2621628










      asked Jan 13 '14 at 6:02









      SoldierCorp

      2,722104480




      2,722104480
























          24 Answers
          24






          active

          oldest

          votes


















          297














          After save, $data->id should be the last id inserted.



          return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);


          For updated laravel version try this



          return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);





          share|improve this answer



















          • 1




            An object always returns an object, ofc. This is the only way to go.
            – Cas Bloem
            Nov 26 '14 at 14:11






          • 27




            Beware that if the id is NOT autoincrement, this will always return 0. In my case the id was a string (UUID) and for this to work I had to add public $incrementing = false; in my model.
            – Luís Cruz
            Apr 20 '15 at 17:18






          • 2




            @milz I have MySQL trigger that generate the uuid for a custom field named aid and I have set $incrementing = false; but It does not returned too!
            – SaidbakR
            Apr 8 '17 at 13:29



















          87














          xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement or DB::insert, there is another way:



          DB::getPdo()->lastInsertId();





          share|improve this answer



















          • 26




            Actually you can do it right in the insert $id = DB::table('someTable')->insertGetId( ['field' => Input['data']);
            – Casey
            May 15 '14 at 15:05








          • 1




            @Casey doing it this way will not update timestamps in the DB
            – Rafael
            Dec 7 '14 at 4:30












          • @Rafael, if you want to update timestamps using insertGetId, kindly check here
            – Frank Myat Thu
            May 3 '16 at 7:54












          • Exactly what I was looking for the other day! Also, insertGetId only works if the id columns is actually called "id".
            – Captain Hypertext
            Dec 17 '16 at 1:42












          • @Benubird, I have got my solution according your answer.
            – Bhavin Thummar
            Aug 28 at 7:29



















          45














          For anyone who also likes how Jeffrey Way uses Model::create() in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId() but unfortunately this does not respect the $fillable whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create method just wraps the save method (what @xdazz cited above), so you can still pull the last created ID...



          public function store() {

          $input = Request::all();
          $id = Company::create($input)->id;

          return redirect('company/'.$id);
          }





          share|improve this answer

















          • 2




            This example didn't work for me in 5.1, but this did: $new = Company::create($input); return redirect('company/'.$new->id);
            – timgavin
            Sep 19 '15 at 18:15










          • This assumes that the request fields name are the same as their respective database columns. Which is not always the case ( legacy codes for example)..
            – mosid
            Nov 30 '17 at 4:47



















          34














          If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:



          $id = DB::table('users')->insertGetId([
          'email' => 'john@example.com',
          'votes' => 0
          ]);


          Refer: https://laravel.com/docs/5.1/queries#inserts






          share|improve this answer























          • What you described looks like capturing last insert using Fluent. Question was about Eloquent. It would look more like: $id = Model::create('votes' => 0])->id; As described in this answer above: stackoverflow.com/a/21084888/436443
            – Jeffz
            Jul 10 at 22:02



















          30














          **** For Laravel ****



          Firstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as



          $user = new User();        

          $user->name = 'John';

          $user->save();


          // Now Getting The Last inserted id



          $insertedId = $user->id;

          echo $insertedId ;





          share|improve this answer































            13














            In laravel 5: you can do this:



            use AppHttpRequestsUserStoreRequest;
            class UserController extends Controller {
            private $user;
            public function __construct( User $user )
            {
            $this->user = $user;
            }
            public function store( UserStoreRequest $request )
            {
            $user= $this->user->create([
            'name' => $request['name'],
            'email' => $request['email'],
            'password' => Hash::make($request['password'])
            ]);
            $lastInsertedId= $user->id;
            }
            }





            share|improve this answer





























              10














              Here's an example:



              public static function saveTutorial(){

              $data = Input::all();

              $Tut = new Tutorial;
              $Tut->title = $data['title'];
              $Tut->tutorial = $data['tutorial'];
              $Tut->save();
              $LastInsertId = $Tut->id;

              return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);
              }





              share|improve this answer































                10














                This worked for me in laravel 4.2



                $id = User::insertGetId([
                'username' => Input::get('username'),
                'password' => Hash::make('password'),
                'active' => 0
                ]);





                share|improve this answer































                  9














                  Here is how we can get last inserted id in Laravel 4



                  public function store()
                  {
                  $input = Input::all();

                  $validation = Validator::make($input, user::$rules);

                  if ($validation->passes())
                  {

                  $user= $this->user->create(array(
                  'name' => Input::get('name'),
                  'email' => Input::get('email'),
                  'password' => Hash::make(Input::get('password')),
                  ));
                  $lastInsertedId= $user->id; //get last inserted record's user id value
                  $userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved
                  $user->update($userId); //update newly created record by storing the value of last inserted id
                  return Redirect::route('users.index');
                  }
                  return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
                  }





                  share|improve this answer





























                    7














                    Use insertGetId to insert and get inserted id at the same time



                    From doc




                    If the table has an auto-incrementing id, use the insertGetId method
                    to insert a record and then retrieve the ID:




                    By Model



                    $id = Model::insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);


                    By DB



                    $id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);


                    For more details : https://laravel.com/docs/5.5/queries#inserts






                    share|improve this answer





























                      3














                      After saving model, the initialized instance has the id:



                      $report = new Report();
                      $report->user_id = $request->user_id;
                      $report->patient_id = $request->patient_id;
                      $report->diseases_id = $request->modality;
                      $isReportCreated = $report->save();
                      return $report->id; // this will return the saved report id





                      share|improve this answer































                        2














                        After saving a record in database, you can access id by $data->id



                        return Response::json(['success' => true, 'last_insert_id' => $data->id], 200)





                        share|improve this answer





























                          2














                          In Laravel 5.2 i would make it as clean as possible:



                          public function saveContact(Request $request, Contact $contact)
                          {
                          $create = $contact->create($request->all());
                          return response()->json($create->id, 201);
                          }





                          share|improve this answer





























                            2














                            For Laravel, If you insert a new record and call $data->save() this function executes an INSERT query and returns the primary key value (i.e. id by default).



                            You can use following code:



                            if($data->save()) {
                            return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200);
                            }





                            share|improve this answer































                              2














                              After



                              $data->save()


                              $data->id will give you the inserted id,



                              Note: If your autoincrement column name is sno then you should use
                              $data->sno and not $data->id






                              share|improve this answer





























                                1














                                You can do this:



                                $result=app('db')->insert("INSERT INTO table...");

                                $lastInsertId=app('db')->getPdo()->lastInsertId();





                                share|improve this answer































                                  1














                                  $objPost = new Post;
                                  $objPost->title = 'Title';
                                  $objPost->description = 'Description';
                                  $objPost->save();
                                  $recId = $objPost->id; // If Id in table column name if other then id then user the other column name

                                  return Response::json(['success' => true,'id' => $recId], 200);





                                  share|improve this answer































                                    1














                                    For insert()



                                    Example:



                                    $data1 = array(
                                    'company_id' => $company_id,
                                    'branch_id' => $branch_id
                                    );




                                            $insert_id = CreditVoucher::insert($data1);
                                    $id = DB::getPdo()->lastInsertId();
                                    dd($id);





                                    share|improve this answer





























                                      0














                                      Using Eloquent Model



                                      $user = new Report();        
                                      $user->email= 'johndoe@example.com';
                                      $user->save();
                                      $lastId = $user->id;


                                      Using Query Builder



                                      $lastId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']);





                                      share|improve this answer





























                                        0














                                        For get last inserted id in database
                                        You can use



                                        $data = new YourModelName;
                                        $data->name = 'Some Value';
                                        $data->email = 'abc@mail.com';
                                        $data->save();
                                        $lastInsertedId = $data->id;


                                        here $lastInsertedId will gives you last inserted auto increment id.






                                        share|improve this answer





























                                          0














                                          After Saving $data->save(). all data is pushed inside $data. As this is an object and the current row is just saved recently inside $data. so last insertId will be found inside $data->id.



                                          Response code will be:



                                          return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);





                                          share|improve this answer































                                            0














                                            The shortest way is probably a call of the refresh() on the model:



                                            public function create(array $data): MyModel
                                            {
                                            $myModel = new MyModel($dataArray);
                                            $myModel->saveOrFail();
                                            return $myModel->refresh();
                                            }





                                            share|improve this answer





























                                              -1














                                              public function store( UserStoreRequest $request ) {
                                              $input = $request->all();
                                              $user = User::create($input);
                                              $userId=$user->id
                                              }





                                              share|improve this answer



















                                              • 2




                                                This post was answered 3 years ago. Please edit your answer to add more explanation as to why it might help the user or how its helps solves the OP's question in a better way.
                                                – Syfer
                                                Sep 8 '17 at 11:42






                                              • 1




                                                Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Not to mention the age of the question and the low quality of your answer.
                                                – GrumpyCrouton
                                                Sep 8 '17 at 15:53



















                                              -1














                                              Using Eloquent Model



                                              use AppCompany;

                                              public function saveDetailsCompany(Request $request)
                                              {

                                              $createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

                                              // Last Inserted Row ID

                                              echo $createcompany->id;

                                              }


                                              Using Query Builder



                                              $createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

                                              echo $createcompany->id;


                                              For more methods to get Last Inserted Row id in Laravel : http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel






                                              share|improve this answer





















                                                Your Answer






                                                StackExchange.ifUsing("editor", function () {
                                                StackExchange.using("externalEditor", function () {
                                                StackExchange.using("snippets", function () {
                                                StackExchange.snippets.init();
                                                });
                                                });
                                                }, "code-snippets");

                                                StackExchange.ready(function() {
                                                var channelOptions = {
                                                tags: "".split(" "),
                                                id: "1"
                                                };
                                                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                                                StackExchange.using("externalEditor", function() {
                                                // Have to fire editor after snippets, if snippets enabled
                                                if (StackExchange.settings.snippets.snippetsEnabled) {
                                                StackExchange.using("snippets", function() {
                                                createEditor();
                                                });
                                                }
                                                else {
                                                createEditor();
                                                }
                                                });

                                                function createEditor() {
                                                StackExchange.prepareEditor({
                                                heartbeatType: 'answer',
                                                autoActivateHeartbeat: false,
                                                convertImagesToLinks: true,
                                                noModals: true,
                                                showLowRepImageUploadWarning: true,
                                                reputationToPostImages: 10,
                                                bindNavPrevention: true,
                                                postfix: "",
                                                imageUploader: {
                                                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                                                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                                                allowUrls: true
                                                },
                                                onDemand: true,
                                                discardSelector: ".discard-answer"
                                                ,immediatelyShowMarkdownHelp:true
                                                });


                                                }
                                                });














                                                draft saved

                                                draft discarded


















                                                StackExchange.ready(
                                                function () {
                                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f21084833%2fget-the-last-inserted-id-using-laravel-eloquent%23new-answer', 'question_page');
                                                }
                                                );

                                                Post as a guest















                                                Required, but never shown

























                                                24 Answers
                                                24






                                                active

                                                oldest

                                                votes








                                                24 Answers
                                                24






                                                active

                                                oldest

                                                votes









                                                active

                                                oldest

                                                votes






                                                active

                                                oldest

                                                votes









                                                297














                                                After save, $data->id should be the last id inserted.



                                                return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);


                                                For updated laravel version try this



                                                return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);





                                                share|improve this answer



















                                                • 1




                                                  An object always returns an object, ofc. This is the only way to go.
                                                  – Cas Bloem
                                                  Nov 26 '14 at 14:11






                                                • 27




                                                  Beware that if the id is NOT autoincrement, this will always return 0. In my case the id was a string (UUID) and for this to work I had to add public $incrementing = false; in my model.
                                                  – Luís Cruz
                                                  Apr 20 '15 at 17:18






                                                • 2




                                                  @milz I have MySQL trigger that generate the uuid for a custom field named aid and I have set $incrementing = false; but It does not returned too!
                                                  – SaidbakR
                                                  Apr 8 '17 at 13:29
















                                                297














                                                After save, $data->id should be the last id inserted.



                                                return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);


                                                For updated laravel version try this



                                                return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);





                                                share|improve this answer



















                                                • 1




                                                  An object always returns an object, ofc. This is the only way to go.
                                                  – Cas Bloem
                                                  Nov 26 '14 at 14:11






                                                • 27




                                                  Beware that if the id is NOT autoincrement, this will always return 0. In my case the id was a string (UUID) and for this to work I had to add public $incrementing = false; in my model.
                                                  – Luís Cruz
                                                  Apr 20 '15 at 17:18






                                                • 2




                                                  @milz I have MySQL trigger that generate the uuid for a custom field named aid and I have set $incrementing = false; but It does not returned too!
                                                  – SaidbakR
                                                  Apr 8 '17 at 13:29














                                                297












                                                297








                                                297






                                                After save, $data->id should be the last id inserted.



                                                return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);


                                                For updated laravel version try this



                                                return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);





                                                share|improve this answer














                                                After save, $data->id should be the last id inserted.



                                                return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);


                                                For updated laravel version try this



                                                return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Sep 23 at 14:33









                                                Samiron Barai

                                                34




                                                34










                                                answered Jan 13 '14 at 6:06









                                                xdazz

                                                132k26198231




                                                132k26198231








                                                • 1




                                                  An object always returns an object, ofc. This is the only way to go.
                                                  – Cas Bloem
                                                  Nov 26 '14 at 14:11






                                                • 27




                                                  Beware that if the id is NOT autoincrement, this will always return 0. In my case the id was a string (UUID) and for this to work I had to add public $incrementing = false; in my model.
                                                  – Luís Cruz
                                                  Apr 20 '15 at 17:18






                                                • 2




                                                  @milz I have MySQL trigger that generate the uuid for a custom field named aid and I have set $incrementing = false; but It does not returned too!
                                                  – SaidbakR
                                                  Apr 8 '17 at 13:29














                                                • 1




                                                  An object always returns an object, ofc. This is the only way to go.
                                                  – Cas Bloem
                                                  Nov 26 '14 at 14:11






                                                • 27




                                                  Beware that if the id is NOT autoincrement, this will always return 0. In my case the id was a string (UUID) and for this to work I had to add public $incrementing = false; in my model.
                                                  – Luís Cruz
                                                  Apr 20 '15 at 17:18






                                                • 2




                                                  @milz I have MySQL trigger that generate the uuid for a custom field named aid and I have set $incrementing = false; but It does not returned too!
                                                  – SaidbakR
                                                  Apr 8 '17 at 13:29








                                                1




                                                1




                                                An object always returns an object, ofc. This is the only way to go.
                                                – Cas Bloem
                                                Nov 26 '14 at 14:11




                                                An object always returns an object, ofc. This is the only way to go.
                                                – Cas Bloem
                                                Nov 26 '14 at 14:11




                                                27




                                                27




                                                Beware that if the id is NOT autoincrement, this will always return 0. In my case the id was a string (UUID) and for this to work I had to add public $incrementing = false; in my model.
                                                – Luís Cruz
                                                Apr 20 '15 at 17:18




                                                Beware that if the id is NOT autoincrement, this will always return 0. In my case the id was a string (UUID) and for this to work I had to add public $incrementing = false; in my model.
                                                – Luís Cruz
                                                Apr 20 '15 at 17:18




                                                2




                                                2




                                                @milz I have MySQL trigger that generate the uuid for a custom field named aid and I have set $incrementing = false; but It does not returned too!
                                                – SaidbakR
                                                Apr 8 '17 at 13:29




                                                @milz I have MySQL trigger that generate the uuid for a custom field named aid and I have set $incrementing = false; but It does not returned too!
                                                – SaidbakR
                                                Apr 8 '17 at 13:29













                                                87














                                                xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement or DB::insert, there is another way:



                                                DB::getPdo()->lastInsertId();





                                                share|improve this answer



















                                                • 26




                                                  Actually you can do it right in the insert $id = DB::table('someTable')->insertGetId( ['field' => Input['data']);
                                                  – Casey
                                                  May 15 '14 at 15:05








                                                • 1




                                                  @Casey doing it this way will not update timestamps in the DB
                                                  – Rafael
                                                  Dec 7 '14 at 4:30












                                                • @Rafael, if you want to update timestamps using insertGetId, kindly check here
                                                  – Frank Myat Thu
                                                  May 3 '16 at 7:54












                                                • Exactly what I was looking for the other day! Also, insertGetId only works if the id columns is actually called "id".
                                                  – Captain Hypertext
                                                  Dec 17 '16 at 1:42












                                                • @Benubird, I have got my solution according your answer.
                                                  – Bhavin Thummar
                                                  Aug 28 at 7:29
















                                                87














                                                xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement or DB::insert, there is another way:



                                                DB::getPdo()->lastInsertId();





                                                share|improve this answer



















                                                • 26




                                                  Actually you can do it right in the insert $id = DB::table('someTable')->insertGetId( ['field' => Input['data']);
                                                  – Casey
                                                  May 15 '14 at 15:05








                                                • 1




                                                  @Casey doing it this way will not update timestamps in the DB
                                                  – Rafael
                                                  Dec 7 '14 at 4:30












                                                • @Rafael, if you want to update timestamps using insertGetId, kindly check here
                                                  – Frank Myat Thu
                                                  May 3 '16 at 7:54












                                                • Exactly what I was looking for the other day! Also, insertGetId only works if the id columns is actually called "id".
                                                  – Captain Hypertext
                                                  Dec 17 '16 at 1:42












                                                • @Benubird, I have got my solution according your answer.
                                                  – Bhavin Thummar
                                                  Aug 28 at 7:29














                                                87












                                                87








                                                87






                                                xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement or DB::insert, there is another way:



                                                DB::getPdo()->lastInsertId();





                                                share|improve this answer














                                                xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement or DB::insert, there is another way:



                                                DB::getPdo()->lastInsertId();






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited May 23 '17 at 12:18









                                                Community

                                                11




                                                11










                                                answered Apr 23 '14 at 10:33









                                                Benubird

                                                8,2251567112




                                                8,2251567112








                                                • 26




                                                  Actually you can do it right in the insert $id = DB::table('someTable')->insertGetId( ['field' => Input['data']);
                                                  – Casey
                                                  May 15 '14 at 15:05








                                                • 1




                                                  @Casey doing it this way will not update timestamps in the DB
                                                  – Rafael
                                                  Dec 7 '14 at 4:30












                                                • @Rafael, if you want to update timestamps using insertGetId, kindly check here
                                                  – Frank Myat Thu
                                                  May 3 '16 at 7:54












                                                • Exactly what I was looking for the other day! Also, insertGetId only works if the id columns is actually called "id".
                                                  – Captain Hypertext
                                                  Dec 17 '16 at 1:42












                                                • @Benubird, I have got my solution according your answer.
                                                  – Bhavin Thummar
                                                  Aug 28 at 7:29














                                                • 26




                                                  Actually you can do it right in the insert $id = DB::table('someTable')->insertGetId( ['field' => Input['data']);
                                                  – Casey
                                                  May 15 '14 at 15:05








                                                • 1




                                                  @Casey doing it this way will not update timestamps in the DB
                                                  – Rafael
                                                  Dec 7 '14 at 4:30












                                                • @Rafael, if you want to update timestamps using insertGetId, kindly check here
                                                  – Frank Myat Thu
                                                  May 3 '16 at 7:54












                                                • Exactly what I was looking for the other day! Also, insertGetId only works if the id columns is actually called "id".
                                                  – Captain Hypertext
                                                  Dec 17 '16 at 1:42












                                                • @Benubird, I have got my solution according your answer.
                                                  – Bhavin Thummar
                                                  Aug 28 at 7:29








                                                26




                                                26




                                                Actually you can do it right in the insert $id = DB::table('someTable')->insertGetId( ['field' => Input['data']);
                                                – Casey
                                                May 15 '14 at 15:05






                                                Actually you can do it right in the insert $id = DB::table('someTable')->insertGetId( ['field' => Input['data']);
                                                – Casey
                                                May 15 '14 at 15:05






                                                1




                                                1




                                                @Casey doing it this way will not update timestamps in the DB
                                                – Rafael
                                                Dec 7 '14 at 4:30






                                                @Casey doing it this way will not update timestamps in the DB
                                                – Rafael
                                                Dec 7 '14 at 4:30














                                                @Rafael, if you want to update timestamps using insertGetId, kindly check here
                                                – Frank Myat Thu
                                                May 3 '16 at 7:54






                                                @Rafael, if you want to update timestamps using insertGetId, kindly check here
                                                – Frank Myat Thu
                                                May 3 '16 at 7:54














                                                Exactly what I was looking for the other day! Also, insertGetId only works if the id columns is actually called "id".
                                                – Captain Hypertext
                                                Dec 17 '16 at 1:42






                                                Exactly what I was looking for the other day! Also, insertGetId only works if the id columns is actually called "id".
                                                – Captain Hypertext
                                                Dec 17 '16 at 1:42














                                                @Benubird, I have got my solution according your answer.
                                                – Bhavin Thummar
                                                Aug 28 at 7:29




                                                @Benubird, I have got my solution according your answer.
                                                – Bhavin Thummar
                                                Aug 28 at 7:29











                                                45














                                                For anyone who also likes how Jeffrey Way uses Model::create() in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId() but unfortunately this does not respect the $fillable whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create method just wraps the save method (what @xdazz cited above), so you can still pull the last created ID...



                                                public function store() {

                                                $input = Request::all();
                                                $id = Company::create($input)->id;

                                                return redirect('company/'.$id);
                                                }





                                                share|improve this answer

















                                                • 2




                                                  This example didn't work for me in 5.1, but this did: $new = Company::create($input); return redirect('company/'.$new->id);
                                                  – timgavin
                                                  Sep 19 '15 at 18:15










                                                • This assumes that the request fields name are the same as their respective database columns. Which is not always the case ( legacy codes for example)..
                                                  – mosid
                                                  Nov 30 '17 at 4:47
















                                                45














                                                For anyone who also likes how Jeffrey Way uses Model::create() in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId() but unfortunately this does not respect the $fillable whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create method just wraps the save method (what @xdazz cited above), so you can still pull the last created ID...



                                                public function store() {

                                                $input = Request::all();
                                                $id = Company::create($input)->id;

                                                return redirect('company/'.$id);
                                                }





                                                share|improve this answer

















                                                • 2




                                                  This example didn't work for me in 5.1, but this did: $new = Company::create($input); return redirect('company/'.$new->id);
                                                  – timgavin
                                                  Sep 19 '15 at 18:15










                                                • This assumes that the request fields name are the same as their respective database columns. Which is not always the case ( legacy codes for example)..
                                                  – mosid
                                                  Nov 30 '17 at 4:47














                                                45












                                                45








                                                45






                                                For anyone who also likes how Jeffrey Way uses Model::create() in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId() but unfortunately this does not respect the $fillable whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create method just wraps the save method (what @xdazz cited above), so you can still pull the last created ID...



                                                public function store() {

                                                $input = Request::all();
                                                $id = Company::create($input)->id;

                                                return redirect('company/'.$id);
                                                }





                                                share|improve this answer












                                                For anyone who also likes how Jeffrey Way uses Model::create() in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId() but unfortunately this does not respect the $fillable whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create method just wraps the save method (what @xdazz cited above), so you can still pull the last created ID...



                                                public function store() {

                                                $input = Request::all();
                                                $id = Company::create($input)->id;

                                                return redirect('company/'.$id);
                                                }






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Jul 5 '15 at 10:20









                                                dave

                                                1,77821720




                                                1,77821720








                                                • 2




                                                  This example didn't work for me in 5.1, but this did: $new = Company::create($input); return redirect('company/'.$new->id);
                                                  – timgavin
                                                  Sep 19 '15 at 18:15










                                                • This assumes that the request fields name are the same as their respective database columns. Which is not always the case ( legacy codes for example)..
                                                  – mosid
                                                  Nov 30 '17 at 4:47














                                                • 2




                                                  This example didn't work for me in 5.1, but this did: $new = Company::create($input); return redirect('company/'.$new->id);
                                                  – timgavin
                                                  Sep 19 '15 at 18:15










                                                • This assumes that the request fields name are the same as their respective database columns. Which is not always the case ( legacy codes for example)..
                                                  – mosid
                                                  Nov 30 '17 at 4:47








                                                2




                                                2




                                                This example didn't work for me in 5.1, but this did: $new = Company::create($input); return redirect('company/'.$new->id);
                                                – timgavin
                                                Sep 19 '15 at 18:15




                                                This example didn't work for me in 5.1, but this did: $new = Company::create($input); return redirect('company/'.$new->id);
                                                – timgavin
                                                Sep 19 '15 at 18:15












                                                This assumes that the request fields name are the same as their respective database columns. Which is not always the case ( legacy codes for example)..
                                                – mosid
                                                Nov 30 '17 at 4:47




                                                This assumes that the request fields name are the same as their respective database columns. Which is not always the case ( legacy codes for example)..
                                                – mosid
                                                Nov 30 '17 at 4:47











                                                34














                                                If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:



                                                $id = DB::table('users')->insertGetId([
                                                'email' => 'john@example.com',
                                                'votes' => 0
                                                ]);


                                                Refer: https://laravel.com/docs/5.1/queries#inserts






                                                share|improve this answer























                                                • What you described looks like capturing last insert using Fluent. Question was about Eloquent. It would look more like: $id = Model::create('votes' => 0])->id; As described in this answer above: stackoverflow.com/a/21084888/436443
                                                  – Jeffz
                                                  Jul 10 at 22:02
















                                                34














                                                If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:



                                                $id = DB::table('users')->insertGetId([
                                                'email' => 'john@example.com',
                                                'votes' => 0
                                                ]);


                                                Refer: https://laravel.com/docs/5.1/queries#inserts






                                                share|improve this answer























                                                • What you described looks like capturing last insert using Fluent. Question was about Eloquent. It would look more like: $id = Model::create('votes' => 0])->id; As described in this answer above: stackoverflow.com/a/21084888/436443
                                                  – Jeffz
                                                  Jul 10 at 22:02














                                                34












                                                34








                                                34






                                                If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:



                                                $id = DB::table('users')->insertGetId([
                                                'email' => 'john@example.com',
                                                'votes' => 0
                                                ]);


                                                Refer: https://laravel.com/docs/5.1/queries#inserts






                                                share|improve this answer














                                                If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:



                                                $id = DB::table('users')->insertGetId([
                                                'email' => 'john@example.com',
                                                'votes' => 0
                                                ]);


                                                Refer: https://laravel.com/docs/5.1/queries#inserts







                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Aug 17 at 17:45









                                                Barry

                                                3,10571637




                                                3,10571637










                                                answered Jun 22 '16 at 9:34









                                                Aamir

                                                89711231




                                                89711231












                                                • What you described looks like capturing last insert using Fluent. Question was about Eloquent. It would look more like: $id = Model::create('votes' => 0])->id; As described in this answer above: stackoverflow.com/a/21084888/436443
                                                  – Jeffz
                                                  Jul 10 at 22:02


















                                                • What you described looks like capturing last insert using Fluent. Question was about Eloquent. It would look more like: $id = Model::create('votes' => 0])->id; As described in this answer above: stackoverflow.com/a/21084888/436443
                                                  – Jeffz
                                                  Jul 10 at 22:02
















                                                What you described looks like capturing last insert using Fluent. Question was about Eloquent. It would look more like: $id = Model::create('votes' => 0])->id; As described in this answer above: stackoverflow.com/a/21084888/436443
                                                – Jeffz
                                                Jul 10 at 22:02




                                                What you described looks like capturing last insert using Fluent. Question was about Eloquent. It would look more like: $id = Model::create('votes' => 0])->id; As described in this answer above: stackoverflow.com/a/21084888/436443
                                                – Jeffz
                                                Jul 10 at 22:02











                                                30














                                                **** For Laravel ****



                                                Firstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as



                                                $user = new User();        

                                                $user->name = 'John';

                                                $user->save();


                                                // Now Getting The Last inserted id



                                                $insertedId = $user->id;

                                                echo $insertedId ;





                                                share|improve this answer




























                                                  30














                                                  **** For Laravel ****



                                                  Firstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as



                                                  $user = new User();        

                                                  $user->name = 'John';

                                                  $user->save();


                                                  // Now Getting The Last inserted id



                                                  $insertedId = $user->id;

                                                  echo $insertedId ;





                                                  share|improve this answer


























                                                    30












                                                    30








                                                    30






                                                    **** For Laravel ****



                                                    Firstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as



                                                    $user = new User();        

                                                    $user->name = 'John';

                                                    $user->save();


                                                    // Now Getting The Last inserted id



                                                    $insertedId = $user->id;

                                                    echo $insertedId ;





                                                    share|improve this answer














                                                    **** For Laravel ****



                                                    Firstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as



                                                    $user = new User();        

                                                    $user->name = 'John';

                                                    $user->save();


                                                    // Now Getting The Last inserted id



                                                    $insertedId = $user->id;

                                                    echo $insertedId ;






                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Jul 25 '16 at 6:16

























                                                    answered May 28 '16 at 9:15









                                                    Majbah Habib

                                                    1,6471721




                                                    1,6471721























                                                        13














                                                        In laravel 5: you can do this:



                                                        use AppHttpRequestsUserStoreRequest;
                                                        class UserController extends Controller {
                                                        private $user;
                                                        public function __construct( User $user )
                                                        {
                                                        $this->user = $user;
                                                        }
                                                        public function store( UserStoreRequest $request )
                                                        {
                                                        $user= $this->user->create([
                                                        'name' => $request['name'],
                                                        'email' => $request['email'],
                                                        'password' => Hash::make($request['password'])
                                                        ]);
                                                        $lastInsertedId= $user->id;
                                                        }
                                                        }





                                                        share|improve this answer


























                                                          13














                                                          In laravel 5: you can do this:



                                                          use AppHttpRequestsUserStoreRequest;
                                                          class UserController extends Controller {
                                                          private $user;
                                                          public function __construct( User $user )
                                                          {
                                                          $this->user = $user;
                                                          }
                                                          public function store( UserStoreRequest $request )
                                                          {
                                                          $user= $this->user->create([
                                                          'name' => $request['name'],
                                                          'email' => $request['email'],
                                                          'password' => Hash::make($request['password'])
                                                          ]);
                                                          $lastInsertedId= $user->id;
                                                          }
                                                          }





                                                          share|improve this answer
























                                                            13












                                                            13








                                                            13






                                                            In laravel 5: you can do this:



                                                            use AppHttpRequestsUserStoreRequest;
                                                            class UserController extends Controller {
                                                            private $user;
                                                            public function __construct( User $user )
                                                            {
                                                            $this->user = $user;
                                                            }
                                                            public function store( UserStoreRequest $request )
                                                            {
                                                            $user= $this->user->create([
                                                            'name' => $request['name'],
                                                            'email' => $request['email'],
                                                            'password' => Hash::make($request['password'])
                                                            ]);
                                                            $lastInsertedId= $user->id;
                                                            }
                                                            }





                                                            share|improve this answer












                                                            In laravel 5: you can do this:



                                                            use AppHttpRequestsUserStoreRequest;
                                                            class UserController extends Controller {
                                                            private $user;
                                                            public function __construct( User $user )
                                                            {
                                                            $this->user = $user;
                                                            }
                                                            public function store( UserStoreRequest $request )
                                                            {
                                                            $user= $this->user->create([
                                                            'name' => $request['name'],
                                                            'email' => $request['email'],
                                                            'password' => Hash::make($request['password'])
                                                            ]);
                                                            $lastInsertedId= $user->id;
                                                            }
                                                            }






                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Feb 21 '15 at 7:48









                                                            Mujibur

                                                            47249




                                                            47249























                                                                10














                                                                Here's an example:



                                                                public static function saveTutorial(){

                                                                $data = Input::all();

                                                                $Tut = new Tutorial;
                                                                $Tut->title = $data['title'];
                                                                $Tut->tutorial = $data['tutorial'];
                                                                $Tut->save();
                                                                $LastInsertId = $Tut->id;

                                                                return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);
                                                                }





                                                                share|improve this answer




























                                                                  10














                                                                  Here's an example:



                                                                  public static function saveTutorial(){

                                                                  $data = Input::all();

                                                                  $Tut = new Tutorial;
                                                                  $Tut->title = $data['title'];
                                                                  $Tut->tutorial = $data['tutorial'];
                                                                  $Tut->save();
                                                                  $LastInsertId = $Tut->id;

                                                                  return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);
                                                                  }





                                                                  share|improve this answer


























                                                                    10












                                                                    10








                                                                    10






                                                                    Here's an example:



                                                                    public static function saveTutorial(){

                                                                    $data = Input::all();

                                                                    $Tut = new Tutorial;
                                                                    $Tut->title = $data['title'];
                                                                    $Tut->tutorial = $data['tutorial'];
                                                                    $Tut->save();
                                                                    $LastInsertId = $Tut->id;

                                                                    return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);
                                                                    }





                                                                    share|improve this answer














                                                                    Here's an example:



                                                                    public static function saveTutorial(){

                                                                    $data = Input::all();

                                                                    $Tut = new Tutorial;
                                                                    $Tut->title = $data['title'];
                                                                    $Tut->tutorial = $data['tutorial'];
                                                                    $Tut->save();
                                                                    $LastInsertId = $Tut->id;

                                                                    return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);
                                                                    }






                                                                    share|improve this answer














                                                                    share|improve this answer



                                                                    share|improve this answer








                                                                    edited Aug 17 at 17:47









                                                                    Barry

                                                                    3,10571637




                                                                    3,10571637










                                                                    answered Apr 16 '14 at 10:42









                                                                    ngakak

                                                                    458510




                                                                    458510























                                                                        10














                                                                        This worked for me in laravel 4.2



                                                                        $id = User::insertGetId([
                                                                        'username' => Input::get('username'),
                                                                        'password' => Hash::make('password'),
                                                                        'active' => 0
                                                                        ]);





                                                                        share|improve this answer




























                                                                          10














                                                                          This worked for me in laravel 4.2



                                                                          $id = User::insertGetId([
                                                                          'username' => Input::get('username'),
                                                                          'password' => Hash::make('password'),
                                                                          'active' => 0
                                                                          ]);





                                                                          share|improve this answer


























                                                                            10












                                                                            10








                                                                            10






                                                                            This worked for me in laravel 4.2



                                                                            $id = User::insertGetId([
                                                                            'username' => Input::get('username'),
                                                                            'password' => Hash::make('password'),
                                                                            'active' => 0
                                                                            ]);





                                                                            share|improve this answer














                                                                            This worked for me in laravel 4.2



                                                                            $id = User::insertGetId([
                                                                            'username' => Input::get('username'),
                                                                            'password' => Hash::make('password'),
                                                                            'active' => 0
                                                                            ]);






                                                                            share|improve this answer














                                                                            share|improve this answer



                                                                            share|improve this answer








                                                                            edited Aug 17 at 17:48









                                                                            Barry

                                                                            3,10571637




                                                                            3,10571637










                                                                            answered Feb 26 '15 at 17:34









                                                                            user28864

                                                                            1,8991817




                                                                            1,8991817























                                                                                9














                                                                                Here is how we can get last inserted id in Laravel 4



                                                                                public function store()
                                                                                {
                                                                                $input = Input::all();

                                                                                $validation = Validator::make($input, user::$rules);

                                                                                if ($validation->passes())
                                                                                {

                                                                                $user= $this->user->create(array(
                                                                                'name' => Input::get('name'),
                                                                                'email' => Input::get('email'),
                                                                                'password' => Hash::make(Input::get('password')),
                                                                                ));
                                                                                $lastInsertedId= $user->id; //get last inserted record's user id value
                                                                                $userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved
                                                                                $user->update($userId); //update newly created record by storing the value of last inserted id
                                                                                return Redirect::route('users.index');
                                                                                }
                                                                                return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
                                                                                }





                                                                                share|improve this answer


























                                                                                  9














                                                                                  Here is how we can get last inserted id in Laravel 4



                                                                                  public function store()
                                                                                  {
                                                                                  $input = Input::all();

                                                                                  $validation = Validator::make($input, user::$rules);

                                                                                  if ($validation->passes())
                                                                                  {

                                                                                  $user= $this->user->create(array(
                                                                                  'name' => Input::get('name'),
                                                                                  'email' => Input::get('email'),
                                                                                  'password' => Hash::make(Input::get('password')),
                                                                                  ));
                                                                                  $lastInsertedId= $user->id; //get last inserted record's user id value
                                                                                  $userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved
                                                                                  $user->update($userId); //update newly created record by storing the value of last inserted id
                                                                                  return Redirect::route('users.index');
                                                                                  }
                                                                                  return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
                                                                                  }





                                                                                  share|improve this answer
























                                                                                    9












                                                                                    9








                                                                                    9






                                                                                    Here is how we can get last inserted id in Laravel 4



                                                                                    public function store()
                                                                                    {
                                                                                    $input = Input::all();

                                                                                    $validation = Validator::make($input, user::$rules);

                                                                                    if ($validation->passes())
                                                                                    {

                                                                                    $user= $this->user->create(array(
                                                                                    'name' => Input::get('name'),
                                                                                    'email' => Input::get('email'),
                                                                                    'password' => Hash::make(Input::get('password')),
                                                                                    ));
                                                                                    $lastInsertedId= $user->id; //get last inserted record's user id value
                                                                                    $userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved
                                                                                    $user->update($userId); //update newly created record by storing the value of last inserted id
                                                                                    return Redirect::route('users.index');
                                                                                    }
                                                                                    return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
                                                                                    }





                                                                                    share|improve this answer












                                                                                    Here is how we can get last inserted id in Laravel 4



                                                                                    public function store()
                                                                                    {
                                                                                    $input = Input::all();

                                                                                    $validation = Validator::make($input, user::$rules);

                                                                                    if ($validation->passes())
                                                                                    {

                                                                                    $user= $this->user->create(array(
                                                                                    'name' => Input::get('name'),
                                                                                    'email' => Input::get('email'),
                                                                                    'password' => Hash::make(Input::get('password')),
                                                                                    ));
                                                                                    $lastInsertedId= $user->id; //get last inserted record's user id value
                                                                                    $userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved
                                                                                    $user->update($userId); //update newly created record by storing the value of last inserted id
                                                                                    return Redirect::route('users.index');
                                                                                    }
                                                                                    return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
                                                                                    }






                                                                                    share|improve this answer












                                                                                    share|improve this answer



                                                                                    share|improve this answer










                                                                                    answered Apr 30 '14 at 7:45









                                                                                    Qamar Uzman

                                                                                    57263




                                                                                    57263























                                                                                        7














                                                                                        Use insertGetId to insert and get inserted id at the same time



                                                                                        From doc




                                                                                        If the table has an auto-incrementing id, use the insertGetId method
                                                                                        to insert a record and then retrieve the ID:




                                                                                        By Model



                                                                                        $id = Model::insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);


                                                                                        By DB



                                                                                        $id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);


                                                                                        For more details : https://laravel.com/docs/5.5/queries#inserts






                                                                                        share|improve this answer


























                                                                                          7














                                                                                          Use insertGetId to insert and get inserted id at the same time



                                                                                          From doc




                                                                                          If the table has an auto-incrementing id, use the insertGetId method
                                                                                          to insert a record and then retrieve the ID:




                                                                                          By Model



                                                                                          $id = Model::insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);


                                                                                          By DB



                                                                                          $id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);


                                                                                          For more details : https://laravel.com/docs/5.5/queries#inserts






                                                                                          share|improve this answer
























                                                                                            7












                                                                                            7








                                                                                            7






                                                                                            Use insertGetId to insert and get inserted id at the same time



                                                                                            From doc




                                                                                            If the table has an auto-incrementing id, use the insertGetId method
                                                                                            to insert a record and then retrieve the ID:




                                                                                            By Model



                                                                                            $id = Model::insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);


                                                                                            By DB



                                                                                            $id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);


                                                                                            For more details : https://laravel.com/docs/5.5/queries#inserts






                                                                                            share|improve this answer












                                                                                            Use insertGetId to insert and get inserted id at the same time



                                                                                            From doc




                                                                                            If the table has an auto-incrementing id, use the insertGetId method
                                                                                            to insert a record and then retrieve the ID:




                                                                                            By Model



                                                                                            $id = Model::insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);


                                                                                            By DB



                                                                                            $id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);


                                                                                            For more details : https://laravel.com/docs/5.5/queries#inserts







                                                                                            share|improve this answer












                                                                                            share|improve this answer



                                                                                            share|improve this answer










                                                                                            answered Sep 29 '17 at 6:32









                                                                                            C2486

                                                                                            18.8k32565




                                                                                            18.8k32565























                                                                                                3














                                                                                                After saving model, the initialized instance has the id:



                                                                                                $report = new Report();
                                                                                                $report->user_id = $request->user_id;
                                                                                                $report->patient_id = $request->patient_id;
                                                                                                $report->diseases_id = $request->modality;
                                                                                                $isReportCreated = $report->save();
                                                                                                return $report->id; // this will return the saved report id





                                                                                                share|improve this answer




























                                                                                                  3














                                                                                                  After saving model, the initialized instance has the id:



                                                                                                  $report = new Report();
                                                                                                  $report->user_id = $request->user_id;
                                                                                                  $report->patient_id = $request->patient_id;
                                                                                                  $report->diseases_id = $request->modality;
                                                                                                  $isReportCreated = $report->save();
                                                                                                  return $report->id; // this will return the saved report id





                                                                                                  share|improve this answer


























                                                                                                    3












                                                                                                    3








                                                                                                    3






                                                                                                    After saving model, the initialized instance has the id:



                                                                                                    $report = new Report();
                                                                                                    $report->user_id = $request->user_id;
                                                                                                    $report->patient_id = $request->patient_id;
                                                                                                    $report->diseases_id = $request->modality;
                                                                                                    $isReportCreated = $report->save();
                                                                                                    return $report->id; // this will return the saved report id





                                                                                                    share|improve this answer














                                                                                                    After saving model, the initialized instance has the id:



                                                                                                    $report = new Report();
                                                                                                    $report->user_id = $request->user_id;
                                                                                                    $report->patient_id = $request->patient_id;
                                                                                                    $report->diseases_id = $request->modality;
                                                                                                    $isReportCreated = $report->save();
                                                                                                    return $report->id; // this will return the saved report id






                                                                                                    share|improve this answer














                                                                                                    share|improve this answer



                                                                                                    share|improve this answer








                                                                                                    edited Aug 17 at 17:49









                                                                                                    Barry

                                                                                                    3,10571637




                                                                                                    3,10571637










                                                                                                    answered Nov 3 '15 at 9:25









                                                                                                    Amir

                                                                                                    6,18943645




                                                                                                    6,18943645























                                                                                                        2














                                                                                                        After saving a record in database, you can access id by $data->id



                                                                                                        return Response::json(['success' => true, 'last_insert_id' => $data->id], 200)





                                                                                                        share|improve this answer


























                                                                                                          2














                                                                                                          After saving a record in database, you can access id by $data->id



                                                                                                          return Response::json(['success' => true, 'last_insert_id' => $data->id], 200)





                                                                                                          share|improve this answer
























                                                                                                            2












                                                                                                            2








                                                                                                            2






                                                                                                            After saving a record in database, you can access id by $data->id



                                                                                                            return Response::json(['success' => true, 'last_insert_id' => $data->id], 200)





                                                                                                            share|improve this answer












                                                                                                            After saving a record in database, you can access id by $data->id



                                                                                                            return Response::json(['success' => true, 'last_insert_id' => $data->id], 200)






                                                                                                            share|improve this answer












                                                                                                            share|improve this answer



                                                                                                            share|improve this answer










                                                                                                            answered Nov 3 '15 at 10:30









                                                                                                            Tayyab_Hussain

                                                                                                            809815




                                                                                                            809815























                                                                                                                2














                                                                                                                In Laravel 5.2 i would make it as clean as possible:



                                                                                                                public function saveContact(Request $request, Contact $contact)
                                                                                                                {
                                                                                                                $create = $contact->create($request->all());
                                                                                                                return response()->json($create->id, 201);
                                                                                                                }





                                                                                                                share|improve this answer


























                                                                                                                  2














                                                                                                                  In Laravel 5.2 i would make it as clean as possible:



                                                                                                                  public function saveContact(Request $request, Contact $contact)
                                                                                                                  {
                                                                                                                  $create = $contact->create($request->all());
                                                                                                                  return response()->json($create->id, 201);
                                                                                                                  }





                                                                                                                  share|improve this answer
























                                                                                                                    2












                                                                                                                    2








                                                                                                                    2






                                                                                                                    In Laravel 5.2 i would make it as clean as possible:



                                                                                                                    public function saveContact(Request $request, Contact $contact)
                                                                                                                    {
                                                                                                                    $create = $contact->create($request->all());
                                                                                                                    return response()->json($create->id, 201);
                                                                                                                    }





                                                                                                                    share|improve this answer












                                                                                                                    In Laravel 5.2 i would make it as clean as possible:



                                                                                                                    public function saveContact(Request $request, Contact $contact)
                                                                                                                    {
                                                                                                                    $create = $contact->create($request->all());
                                                                                                                    return response()->json($create->id, 201);
                                                                                                                    }






                                                                                                                    share|improve this answer












                                                                                                                    share|improve this answer



                                                                                                                    share|improve this answer










                                                                                                                    answered May 8 '16 at 11:30









                                                                                                                    bobbybackblech

                                                                                                                    91031322




                                                                                                                    91031322























                                                                                                                        2














                                                                                                                        For Laravel, If you insert a new record and call $data->save() this function executes an INSERT query and returns the primary key value (i.e. id by default).



                                                                                                                        You can use following code:



                                                                                                                        if($data->save()) {
                                                                                                                        return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200);
                                                                                                                        }





                                                                                                                        share|improve this answer




























                                                                                                                          2














                                                                                                                          For Laravel, If you insert a new record and call $data->save() this function executes an INSERT query and returns the primary key value (i.e. id by default).



                                                                                                                          You can use following code:



                                                                                                                          if($data->save()) {
                                                                                                                          return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200);
                                                                                                                          }





                                                                                                                          share|improve this answer


























                                                                                                                            2












                                                                                                                            2








                                                                                                                            2






                                                                                                                            For Laravel, If you insert a new record and call $data->save() this function executes an INSERT query and returns the primary key value (i.e. id by default).



                                                                                                                            You can use following code:



                                                                                                                            if($data->save()) {
                                                                                                                            return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200);
                                                                                                                            }





                                                                                                                            share|improve this answer














                                                                                                                            For Laravel, If you insert a new record and call $data->save() this function executes an INSERT query and returns the primary key value (i.e. id by default).



                                                                                                                            You can use following code:



                                                                                                                            if($data->save()) {
                                                                                                                            return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200);
                                                                                                                            }






                                                                                                                            share|improve this answer














                                                                                                                            share|improve this answer



                                                                                                                            share|improve this answer








                                                                                                                            edited Mar 21 '17 at 18:47









                                                                                                                            Sᴀᴍ Onᴇᴌᴀ

                                                                                                                            6,52682142




                                                                                                                            6,52682142










                                                                                                                            answered Mar 15 '17 at 9:06









                                                                                                                            HItesh Tank

                                                                                                                            261211




                                                                                                                            261211























                                                                                                                                2














                                                                                                                                After



                                                                                                                                $data->save()


                                                                                                                                $data->id will give you the inserted id,



                                                                                                                                Note: If your autoincrement column name is sno then you should use
                                                                                                                                $data->sno and not $data->id






                                                                                                                                share|improve this answer


























                                                                                                                                  2














                                                                                                                                  After



                                                                                                                                  $data->save()


                                                                                                                                  $data->id will give you the inserted id,



                                                                                                                                  Note: If your autoincrement column name is sno then you should use
                                                                                                                                  $data->sno and not $data->id






                                                                                                                                  share|improve this answer
























                                                                                                                                    2












                                                                                                                                    2








                                                                                                                                    2






                                                                                                                                    After



                                                                                                                                    $data->save()


                                                                                                                                    $data->id will give you the inserted id,



                                                                                                                                    Note: If your autoincrement column name is sno then you should use
                                                                                                                                    $data->sno and not $data->id






                                                                                                                                    share|improve this answer












                                                                                                                                    After



                                                                                                                                    $data->save()


                                                                                                                                    $data->id will give you the inserted id,



                                                                                                                                    Note: If your autoincrement column name is sno then you should use
                                                                                                                                    $data->sno and not $data->id







                                                                                                                                    share|improve this answer












                                                                                                                                    share|improve this answer



                                                                                                                                    share|improve this answer










                                                                                                                                    answered Mar 31 '17 at 6:48









                                                                                                                                    Abhishek Goel

                                                                                                                                    10.2k66856




                                                                                                                                    10.2k66856























                                                                                                                                        1














                                                                                                                                        You can do this:



                                                                                                                                        $result=app('db')->insert("INSERT INTO table...");

                                                                                                                                        $lastInsertId=app('db')->getPdo()->lastInsertId();





                                                                                                                                        share|improve this answer




























                                                                                                                                          1














                                                                                                                                          You can do this:



                                                                                                                                          $result=app('db')->insert("INSERT INTO table...");

                                                                                                                                          $lastInsertId=app('db')->getPdo()->lastInsertId();





                                                                                                                                          share|improve this answer


























                                                                                                                                            1












                                                                                                                                            1








                                                                                                                                            1






                                                                                                                                            You can do this:



                                                                                                                                            $result=app('db')->insert("INSERT INTO table...");

                                                                                                                                            $lastInsertId=app('db')->getPdo()->lastInsertId();





                                                                                                                                            share|improve this answer














                                                                                                                                            You can do this:



                                                                                                                                            $result=app('db')->insert("INSERT INTO table...");

                                                                                                                                            $lastInsertId=app('db')->getPdo()->lastInsertId();






                                                                                                                                            share|improve this answer














                                                                                                                                            share|improve this answer



                                                                                                                                            share|improve this answer








                                                                                                                                            edited Aug 17 '17 at 11:27









                                                                                                                                            Moody_Mudskipper

                                                                                                                                            21.2k32764




                                                                                                                                            21.2k32764










                                                                                                                                            answered Aug 17 '17 at 10:30









                                                                                                                                            Dnyaneshwar Harer

                                                                                                                                            11113




                                                                                                                                            11113























                                                                                                                                                1














                                                                                                                                                $objPost = new Post;
                                                                                                                                                $objPost->title = 'Title';
                                                                                                                                                $objPost->description = 'Description';
                                                                                                                                                $objPost->save();
                                                                                                                                                $recId = $objPost->id; // If Id in table column name if other then id then user the other column name

                                                                                                                                                return Response::json(['success' => true,'id' => $recId], 200);





                                                                                                                                                share|improve this answer




























                                                                                                                                                  1














                                                                                                                                                  $objPost = new Post;
                                                                                                                                                  $objPost->title = 'Title';
                                                                                                                                                  $objPost->description = 'Description';
                                                                                                                                                  $objPost->save();
                                                                                                                                                  $recId = $objPost->id; // If Id in table column name if other then id then user the other column name

                                                                                                                                                  return Response::json(['success' => true,'id' => $recId], 200);





                                                                                                                                                  share|improve this answer


























                                                                                                                                                    1












                                                                                                                                                    1








                                                                                                                                                    1






                                                                                                                                                    $objPost = new Post;
                                                                                                                                                    $objPost->title = 'Title';
                                                                                                                                                    $objPost->description = 'Description';
                                                                                                                                                    $objPost->save();
                                                                                                                                                    $recId = $objPost->id; // If Id in table column name if other then id then user the other column name

                                                                                                                                                    return Response::json(['success' => true,'id' => $recId], 200);





                                                                                                                                                    share|improve this answer














                                                                                                                                                    $objPost = new Post;
                                                                                                                                                    $objPost->title = 'Title';
                                                                                                                                                    $objPost->description = 'Description';
                                                                                                                                                    $objPost->save();
                                                                                                                                                    $recId = $objPost->id; // If Id in table column name if other then id then user the other column name

                                                                                                                                                    return Response::json(['success' => true,'id' => $recId], 200);






                                                                                                                                                    share|improve this answer














                                                                                                                                                    share|improve this answer



                                                                                                                                                    share|improve this answer








                                                                                                                                                    edited Aug 17 at 17:50









                                                                                                                                                    Barry

                                                                                                                                                    3,10571637




                                                                                                                                                    3,10571637










                                                                                                                                                    answered Jun 20 at 12:36









                                                                                                                                                    Kamal Maisuriya

                                                                                                                                                    112




                                                                                                                                                    112























                                                                                                                                                        1














                                                                                                                                                        For insert()



                                                                                                                                                        Example:



                                                                                                                                                        $data1 = array(
                                                                                                                                                        'company_id' => $company_id,
                                                                                                                                                        'branch_id' => $branch_id
                                                                                                                                                        );




                                                                                                                                                                $insert_id = CreditVoucher::insert($data1);
                                                                                                                                                        $id = DB::getPdo()->lastInsertId();
                                                                                                                                                        dd($id);





                                                                                                                                                        share|improve this answer


























                                                                                                                                                          1














                                                                                                                                                          For insert()



                                                                                                                                                          Example:



                                                                                                                                                          $data1 = array(
                                                                                                                                                          'company_id' => $company_id,
                                                                                                                                                          'branch_id' => $branch_id
                                                                                                                                                          );




                                                                                                                                                                  $insert_id = CreditVoucher::insert($data1);
                                                                                                                                                          $id = DB::getPdo()->lastInsertId();
                                                                                                                                                          dd($id);





                                                                                                                                                          share|improve this answer
























                                                                                                                                                            1












                                                                                                                                                            1








                                                                                                                                                            1






                                                                                                                                                            For insert()



                                                                                                                                                            Example:



                                                                                                                                                            $data1 = array(
                                                                                                                                                            'company_id' => $company_id,
                                                                                                                                                            'branch_id' => $branch_id
                                                                                                                                                            );




                                                                                                                                                                    $insert_id = CreditVoucher::insert($data1);
                                                                                                                                                            $id = DB::getPdo()->lastInsertId();
                                                                                                                                                            dd($id);





                                                                                                                                                            share|improve this answer












                                                                                                                                                            For insert()



                                                                                                                                                            Example:



                                                                                                                                                            $data1 = array(
                                                                                                                                                            'company_id' => $company_id,
                                                                                                                                                            'branch_id' => $branch_id
                                                                                                                                                            );




                                                                                                                                                                    $insert_id = CreditVoucher::insert($data1);
                                                                                                                                                            $id = DB::getPdo()->lastInsertId();
                                                                                                                                                            dd($id);






                                                                                                                                                            share|improve this answer












                                                                                                                                                            share|improve this answer



                                                                                                                                                            share|improve this answer










                                                                                                                                                            answered Dec 1 at 11:14









                                                                                                                                                            Faridul Khan

                                                                                                                                                            184116




                                                                                                                                                            184116























                                                                                                                                                                0














                                                                                                                                                                Using Eloquent Model



                                                                                                                                                                $user = new Report();        
                                                                                                                                                                $user->email= 'johndoe@example.com';
                                                                                                                                                                $user->save();
                                                                                                                                                                $lastId = $user->id;


                                                                                                                                                                Using Query Builder



                                                                                                                                                                $lastId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']);





                                                                                                                                                                share|improve this answer


























                                                                                                                                                                  0














                                                                                                                                                                  Using Eloquent Model



                                                                                                                                                                  $user = new Report();        
                                                                                                                                                                  $user->email= 'johndoe@example.com';
                                                                                                                                                                  $user->save();
                                                                                                                                                                  $lastId = $user->id;


                                                                                                                                                                  Using Query Builder



                                                                                                                                                                  $lastId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']);





                                                                                                                                                                  share|improve this answer
























                                                                                                                                                                    0












                                                                                                                                                                    0








                                                                                                                                                                    0






                                                                                                                                                                    Using Eloquent Model



                                                                                                                                                                    $user = new Report();        
                                                                                                                                                                    $user->email= 'johndoe@example.com';
                                                                                                                                                                    $user->save();
                                                                                                                                                                    $lastId = $user->id;


                                                                                                                                                                    Using Query Builder



                                                                                                                                                                    $lastId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']);





                                                                                                                                                                    share|improve this answer












                                                                                                                                                                    Using Eloquent Model



                                                                                                                                                                    $user = new Report();        
                                                                                                                                                                    $user->email= 'johndoe@example.com';
                                                                                                                                                                    $user->save();
                                                                                                                                                                    $lastId = $user->id;


                                                                                                                                                                    Using Query Builder



                                                                                                                                                                    $lastId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']);






                                                                                                                                                                    share|improve this answer












                                                                                                                                                                    share|improve this answer



                                                                                                                                                                    share|improve this answer










                                                                                                                                                                    answered Oct 21 '17 at 19:21









                                                                                                                                                                    srmilon

                                                                                                                                                                    1,0981017




                                                                                                                                                                    1,0981017























                                                                                                                                                                        0














                                                                                                                                                                        For get last inserted id in database
                                                                                                                                                                        You can use



                                                                                                                                                                        $data = new YourModelName;
                                                                                                                                                                        $data->name = 'Some Value';
                                                                                                                                                                        $data->email = 'abc@mail.com';
                                                                                                                                                                        $data->save();
                                                                                                                                                                        $lastInsertedId = $data->id;


                                                                                                                                                                        here $lastInsertedId will gives you last inserted auto increment id.






                                                                                                                                                                        share|improve this answer


























                                                                                                                                                                          0














                                                                                                                                                                          For get last inserted id in database
                                                                                                                                                                          You can use



                                                                                                                                                                          $data = new YourModelName;
                                                                                                                                                                          $data->name = 'Some Value';
                                                                                                                                                                          $data->email = 'abc@mail.com';
                                                                                                                                                                          $data->save();
                                                                                                                                                                          $lastInsertedId = $data->id;


                                                                                                                                                                          here $lastInsertedId will gives you last inserted auto increment id.






                                                                                                                                                                          share|improve this answer
























                                                                                                                                                                            0












                                                                                                                                                                            0








                                                                                                                                                                            0






                                                                                                                                                                            For get last inserted id in database
                                                                                                                                                                            You can use



                                                                                                                                                                            $data = new YourModelName;
                                                                                                                                                                            $data->name = 'Some Value';
                                                                                                                                                                            $data->email = 'abc@mail.com';
                                                                                                                                                                            $data->save();
                                                                                                                                                                            $lastInsertedId = $data->id;


                                                                                                                                                                            here $lastInsertedId will gives you last inserted auto increment id.






                                                                                                                                                                            share|improve this answer












                                                                                                                                                                            For get last inserted id in database
                                                                                                                                                                            You can use



                                                                                                                                                                            $data = new YourModelName;
                                                                                                                                                                            $data->name = 'Some Value';
                                                                                                                                                                            $data->email = 'abc@mail.com';
                                                                                                                                                                            $data->save();
                                                                                                                                                                            $lastInsertedId = $data->id;


                                                                                                                                                                            here $lastInsertedId will gives you last inserted auto increment id.







                                                                                                                                                                            share|improve this answer












                                                                                                                                                                            share|improve this answer



                                                                                                                                                                            share|improve this answer










                                                                                                                                                                            answered Feb 26 at 10:09









                                                                                                                                                                            PPL

                                                                                                                                                                            4,6941322




                                                                                                                                                                            4,6941322























                                                                                                                                                                                0














                                                                                                                                                                                After Saving $data->save(). all data is pushed inside $data. As this is an object and the current row is just saved recently inside $data. so last insertId will be found inside $data->id.



                                                                                                                                                                                Response code will be:



                                                                                                                                                                                return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);





                                                                                                                                                                                share|improve this answer




























                                                                                                                                                                                  0














                                                                                                                                                                                  After Saving $data->save(). all data is pushed inside $data. As this is an object and the current row is just saved recently inside $data. so last insertId will be found inside $data->id.



                                                                                                                                                                                  Response code will be:



                                                                                                                                                                                  return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);





                                                                                                                                                                                  share|improve this answer


























                                                                                                                                                                                    0












                                                                                                                                                                                    0








                                                                                                                                                                                    0






                                                                                                                                                                                    After Saving $data->save(). all data is pushed inside $data. As this is an object and the current row is just saved recently inside $data. so last insertId will be found inside $data->id.



                                                                                                                                                                                    Response code will be:



                                                                                                                                                                                    return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);





                                                                                                                                                                                    share|improve this answer














                                                                                                                                                                                    After Saving $data->save(). all data is pushed inside $data. As this is an object and the current row is just saved recently inside $data. so last insertId will be found inside $data->id.



                                                                                                                                                                                    Response code will be:



                                                                                                                                                                                    return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);






                                                                                                                                                                                    share|improve this answer














                                                                                                                                                                                    share|improve this answer



                                                                                                                                                                                    share|improve this answer








                                                                                                                                                                                    edited Aug 17 at 17:51









                                                                                                                                                                                    Barry

                                                                                                                                                                                    3,10571637




                                                                                                                                                                                    3,10571637










                                                                                                                                                                                    answered Apr 9 '17 at 8:51









                                                                                                                                                                                    sabuz

                                                                                                                                                                                    50459




                                                                                                                                                                                    50459























                                                                                                                                                                                        0














                                                                                                                                                                                        The shortest way is probably a call of the refresh() on the model:



                                                                                                                                                                                        public function create(array $data): MyModel
                                                                                                                                                                                        {
                                                                                                                                                                                        $myModel = new MyModel($dataArray);
                                                                                                                                                                                        $myModel->saveOrFail();
                                                                                                                                                                                        return $myModel->refresh();
                                                                                                                                                                                        }





                                                                                                                                                                                        share|improve this answer


























                                                                                                                                                                                          0














                                                                                                                                                                                          The shortest way is probably a call of the refresh() on the model:



                                                                                                                                                                                          public function create(array $data): MyModel
                                                                                                                                                                                          {
                                                                                                                                                                                          $myModel = new MyModel($dataArray);
                                                                                                                                                                                          $myModel->saveOrFail();
                                                                                                                                                                                          return $myModel->refresh();
                                                                                                                                                                                          }





                                                                                                                                                                                          share|improve this answer
























                                                                                                                                                                                            0












                                                                                                                                                                                            0








                                                                                                                                                                                            0






                                                                                                                                                                                            The shortest way is probably a call of the refresh() on the model:



                                                                                                                                                                                            public function create(array $data): MyModel
                                                                                                                                                                                            {
                                                                                                                                                                                            $myModel = new MyModel($dataArray);
                                                                                                                                                                                            $myModel->saveOrFail();
                                                                                                                                                                                            return $myModel->refresh();
                                                                                                                                                                                            }





                                                                                                                                                                                            share|improve this answer












                                                                                                                                                                                            The shortest way is probably a call of the refresh() on the model:



                                                                                                                                                                                            public function create(array $data): MyModel
                                                                                                                                                                                            {
                                                                                                                                                                                            $myModel = new MyModel($dataArray);
                                                                                                                                                                                            $myModel->saveOrFail();
                                                                                                                                                                                            return $myModel->refresh();
                                                                                                                                                                                            }






                                                                                                                                                                                            share|improve this answer












                                                                                                                                                                                            share|improve this answer



                                                                                                                                                                                            share|improve this answer










                                                                                                                                                                                            answered Dec 3 at 14:49









                                                                                                                                                                                            automatix

                                                                                                                                                                                            3,2621551144




                                                                                                                                                                                            3,2621551144























                                                                                                                                                                                                -1














                                                                                                                                                                                                public function store( UserStoreRequest $request ) {
                                                                                                                                                                                                $input = $request->all();
                                                                                                                                                                                                $user = User::create($input);
                                                                                                                                                                                                $userId=$user->id
                                                                                                                                                                                                }





                                                                                                                                                                                                share|improve this answer



















                                                                                                                                                                                                • 2




                                                                                                                                                                                                  This post was answered 3 years ago. Please edit your answer to add more explanation as to why it might help the user or how its helps solves the OP's question in a better way.
                                                                                                                                                                                                  – Syfer
                                                                                                                                                                                                  Sep 8 '17 at 11:42






                                                                                                                                                                                                • 1




                                                                                                                                                                                                  Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Not to mention the age of the question and the low quality of your answer.
                                                                                                                                                                                                  – GrumpyCrouton
                                                                                                                                                                                                  Sep 8 '17 at 15:53
















                                                                                                                                                                                                -1














                                                                                                                                                                                                public function store( UserStoreRequest $request ) {
                                                                                                                                                                                                $input = $request->all();
                                                                                                                                                                                                $user = User::create($input);
                                                                                                                                                                                                $userId=$user->id
                                                                                                                                                                                                }





                                                                                                                                                                                                share|improve this answer



















                                                                                                                                                                                                • 2




                                                                                                                                                                                                  This post was answered 3 years ago. Please edit your answer to add more explanation as to why it might help the user or how its helps solves the OP's question in a better way.
                                                                                                                                                                                                  – Syfer
                                                                                                                                                                                                  Sep 8 '17 at 11:42






                                                                                                                                                                                                • 1




                                                                                                                                                                                                  Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Not to mention the age of the question and the low quality of your answer.
                                                                                                                                                                                                  – GrumpyCrouton
                                                                                                                                                                                                  Sep 8 '17 at 15:53














                                                                                                                                                                                                -1












                                                                                                                                                                                                -1








                                                                                                                                                                                                -1






                                                                                                                                                                                                public function store( UserStoreRequest $request ) {
                                                                                                                                                                                                $input = $request->all();
                                                                                                                                                                                                $user = User::create($input);
                                                                                                                                                                                                $userId=$user->id
                                                                                                                                                                                                }





                                                                                                                                                                                                share|improve this answer














                                                                                                                                                                                                public function store( UserStoreRequest $request ) {
                                                                                                                                                                                                $input = $request->all();
                                                                                                                                                                                                $user = User::create($input);
                                                                                                                                                                                                $userId=$user->id
                                                                                                                                                                                                }






                                                                                                                                                                                                share|improve this answer














                                                                                                                                                                                                share|improve this answer



                                                                                                                                                                                                share|improve this answer








                                                                                                                                                                                                edited Sep 8 '17 at 11:36









                                                                                                                                                                                                Shadow

                                                                                                                                                                                                25.5k92743




                                                                                                                                                                                                25.5k92743










                                                                                                                                                                                                answered Sep 8 '17 at 11:30









                                                                                                                                                                                                temporary account

                                                                                                                                                                                                71




                                                                                                                                                                                                71








                                                                                                                                                                                                • 2




                                                                                                                                                                                                  This post was answered 3 years ago. Please edit your answer to add more explanation as to why it might help the user or how its helps solves the OP's question in a better way.
                                                                                                                                                                                                  – Syfer
                                                                                                                                                                                                  Sep 8 '17 at 11:42






                                                                                                                                                                                                • 1




                                                                                                                                                                                                  Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Not to mention the age of the question and the low quality of your answer.
                                                                                                                                                                                                  – GrumpyCrouton
                                                                                                                                                                                                  Sep 8 '17 at 15:53














                                                                                                                                                                                                • 2




                                                                                                                                                                                                  This post was answered 3 years ago. Please edit your answer to add more explanation as to why it might help the user or how its helps solves the OP's question in a better way.
                                                                                                                                                                                                  – Syfer
                                                                                                                                                                                                  Sep 8 '17 at 11:42






                                                                                                                                                                                                • 1




                                                                                                                                                                                                  Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Not to mention the age of the question and the low quality of your answer.
                                                                                                                                                                                                  – GrumpyCrouton
                                                                                                                                                                                                  Sep 8 '17 at 15:53








                                                                                                                                                                                                2




                                                                                                                                                                                                2




                                                                                                                                                                                                This post was answered 3 years ago. Please edit your answer to add more explanation as to why it might help the user or how its helps solves the OP's question in a better way.
                                                                                                                                                                                                – Syfer
                                                                                                                                                                                                Sep 8 '17 at 11:42




                                                                                                                                                                                                This post was answered 3 years ago. Please edit your answer to add more explanation as to why it might help the user or how its helps solves the OP's question in a better way.
                                                                                                                                                                                                – Syfer
                                                                                                                                                                                                Sep 8 '17 at 11:42




                                                                                                                                                                                                1




                                                                                                                                                                                                1




                                                                                                                                                                                                Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Not to mention the age of the question and the low quality of your answer.
                                                                                                                                                                                                – GrumpyCrouton
                                                                                                                                                                                                Sep 8 '17 at 15:53




                                                                                                                                                                                                Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Not to mention the age of the question and the low quality of your answer.
                                                                                                                                                                                                – GrumpyCrouton
                                                                                                                                                                                                Sep 8 '17 at 15:53











                                                                                                                                                                                                -1














                                                                                                                                                                                                Using Eloquent Model



                                                                                                                                                                                                use AppCompany;

                                                                                                                                                                                                public function saveDetailsCompany(Request $request)
                                                                                                                                                                                                {

                                                                                                                                                                                                $createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

                                                                                                                                                                                                // Last Inserted Row ID

                                                                                                                                                                                                echo $createcompany->id;

                                                                                                                                                                                                }


                                                                                                                                                                                                Using Query Builder



                                                                                                                                                                                                $createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

                                                                                                                                                                                                echo $createcompany->id;


                                                                                                                                                                                                For more methods to get Last Inserted Row id in Laravel : http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel






                                                                                                                                                                                                share|improve this answer


























                                                                                                                                                                                                  -1














                                                                                                                                                                                                  Using Eloquent Model



                                                                                                                                                                                                  use AppCompany;

                                                                                                                                                                                                  public function saveDetailsCompany(Request $request)
                                                                                                                                                                                                  {

                                                                                                                                                                                                  $createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

                                                                                                                                                                                                  // Last Inserted Row ID

                                                                                                                                                                                                  echo $createcompany->id;

                                                                                                                                                                                                  }


                                                                                                                                                                                                  Using Query Builder



                                                                                                                                                                                                  $createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

                                                                                                                                                                                                  echo $createcompany->id;


                                                                                                                                                                                                  For more methods to get Last Inserted Row id in Laravel : http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel






                                                                                                                                                                                                  share|improve this answer
























                                                                                                                                                                                                    -1












                                                                                                                                                                                                    -1








                                                                                                                                                                                                    -1






                                                                                                                                                                                                    Using Eloquent Model



                                                                                                                                                                                                    use AppCompany;

                                                                                                                                                                                                    public function saveDetailsCompany(Request $request)
                                                                                                                                                                                                    {

                                                                                                                                                                                                    $createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

                                                                                                                                                                                                    // Last Inserted Row ID

                                                                                                                                                                                                    echo $createcompany->id;

                                                                                                                                                                                                    }


                                                                                                                                                                                                    Using Query Builder



                                                                                                                                                                                                    $createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

                                                                                                                                                                                                    echo $createcompany->id;


                                                                                                                                                                                                    For more methods to get Last Inserted Row id in Laravel : http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel






                                                                                                                                                                                                    share|improve this answer












                                                                                                                                                                                                    Using Eloquent Model



                                                                                                                                                                                                    use AppCompany;

                                                                                                                                                                                                    public function saveDetailsCompany(Request $request)
                                                                                                                                                                                                    {

                                                                                                                                                                                                    $createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

                                                                                                                                                                                                    // Last Inserted Row ID

                                                                                                                                                                                                    echo $createcompany->id;

                                                                                                                                                                                                    }


                                                                                                                                                                                                    Using Query Builder



                                                                                                                                                                                                    $createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

                                                                                                                                                                                                    echo $createcompany->id;


                                                                                                                                                                                                    For more methods to get Last Inserted Row id in Laravel : http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel







                                                                                                                                                                                                    share|improve this answer












                                                                                                                                                                                                    share|improve this answer



                                                                                                                                                                                                    share|improve this answer










                                                                                                                                                                                                    answered Jun 21 at 4:29









                                                                                                                                                                                                    Karthik

                                                                                                                                                                                                    1,18821235




                                                                                                                                                                                                    1,18821235






























                                                                                                                                                                                                        draft saved

                                                                                                                                                                                                        draft discarded




















































                                                                                                                                                                                                        Thanks for contributing an answer to Stack Overflow!


                                                                                                                                                                                                        • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                                                                                        But avoid



                                                                                                                                                                                                        • Asking for help, clarification, or responding to other answers.

                                                                                                                                                                                                        • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                                                                                        To learn more, see our tips on writing great answers.





                                                                                                                                                                                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                                                                                                                                                                        Please pay close attention to the following guidance:


                                                                                                                                                                                                        • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                                                                                        But avoid



                                                                                                                                                                                                        • Asking for help, clarification, or responding to other answers.

                                                                                                                                                                                                        • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                                                                                        To learn more, see our tips on writing great answers.




                                                                                                                                                                                                        draft saved


                                                                                                                                                                                                        draft discarded














                                                                                                                                                                                                        StackExchange.ready(
                                                                                                                                                                                                        function () {
                                                                                                                                                                                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f21084833%2fget-the-last-inserted-id-using-laravel-eloquent%23new-answer', 'question_page');
                                                                                                                                                                                                        }
                                                                                                                                                                                                        );

                                                                                                                                                                                                        Post as a guest















                                                                                                                                                                                                        Required, but never shown





















































                                                                                                                                                                                                        Required, but never shown














                                                                                                                                                                                                        Required, but never shown












                                                                                                                                                                                                        Required, but never shown







                                                                                                                                                                                                        Required, but never shown

































                                                                                                                                                                                                        Required, but never shown














                                                                                                                                                                                                        Required, but never shown












                                                                                                                                                                                                        Required, but never shown







                                                                                                                                                                                                        Required, but never shown







                                                                                                                                                                                                        Popular posts from this blog

                                                                                                                                                                                                        Create new schema in PostgreSQL using DBeaver

                                                                                                                                                                                                        Deepest pit of an array with Javascript: test on Codility

                                                                                                                                                                                                        Costa Masnaga