无法通过Eloquent

时间:2018-05-26 12:01:50

标签: php jquery laravel eloquent last-insert-id

我使用表单和AJAX将数据发送到我的控制器,并且我试图将插入数据库的数据返回到页面。

一切正常,除了项目的ID。

以下是我的控制器:

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);
}

以及脚本的相关部分:

$(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>');
  }
});

如果我删除字符串的id部分,则会有效,并显示name

console.log提供以下内容:

{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)

我不确定它是从表单输入中获取name还是从控制器返回的数据?

1 个答案:

答案 0 :(得分:4)

当您追加到#tagTable时,您必须使用unsigned long long total = ((unsigned long long) uintA) * uintB * uintC * uintD因为数据是json对象