Search code examples
phpjquerylaraveleloquentlast-insert-id

Can't get last_insert_id from database with Eloquent


I'm sending data to my controller using a form and AJAX, and I'm trying to return the data inserted into the db to the page.

Everything is working ok, except the id of the item.

The following is my controller:

public function store(Request $request)
{
  $this->validate($request, [
      'name' => 'required|max:255',
  ]);

  $tag = new tag;
  $tag->name = $request->name;
  $tag->save();

  $last_insert_id = $tag->id;

  $data = [
      'success' => true,
      'message'=> 'Your AJAX processed correctly',
      'name' => $tag->name,
      'id' => $last_insert_id
    ] ;

    return response()->json($data);
}

and the relevant part of the script:

$(document).ready(function(){

  $("#submit").click(function() {


    var name = $("#tagName").val();
    var token = $("#token").val();

    $.ajax({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
      type: "post",
      data: "name="+name,
      dataType:'json',
      url: "{{ route('tags.store') }}",
      success:function($data){
        console.log($data);
        $("#msg").html("<div class=\"alert alert-primary my-0\">tag Saved</div>");
        $("msg").toggleClass("invisible")
        $("#msg").fadeOut(2000);
        $("#tagTable").append('<tr><td scope="col" class="text-center align-middle">'+$data[id]+'</td><td scope="col"><button type="button" class="btn btn-outline-secondary btn-sm my-1">'+name+'</button></td><td scope="col" class="text-center" >0</td></tr>');
      }
    });
  })
})$("#tagTable").append('<tr><td scope="col" class="text-center align-middle">'+id+'</td><td scope="col"><button type="button" class="btn btn-outline-secondary btn-sm my-1">'+name+'</button></td><td scope="col" class="text-center" >0</td></tr>');
  }
});

If I remove the id part of the string, it works, and displays the name.

The console.log gives the following:

{success: true, message: "Your AJAX processed correctly", name: "test2", id: 36}

Uncaught ReferenceError: id is not defined
    at Object.success (tags:102)
    at l (app.js:1)
    at Object.fireWith [as resolveWith] (app.js:1)
    at E (app.js:1)
    at XMLHttpRequest.<anonymous> (app.js:1)

I'm unsure if it's taking name from the form input, or the data being returned from the controller?


Solution

  • When you append to #tagTable you have to use data.id because data is json object