【问题标题】:Laravel 5.8 Creating default object from empty valueLaravel 5.8 从空值创建默认对象
【发布时间】:2019-10-15 02:22:20
【问题描述】:

当我尝试更新记录时,我得到一个 ErrorException“从空值创建默认对象”并指向我的控制器到 $products->name = $request->input('name') 行。

产品控制器

public function update(Request $request, $id)
    {
        $products = Product::find($id);

        $products->name = $request->input('name');
        $products->category_id = $request->select('category_id');
        $products->description = $request->input('description');
        $products->price_neto = $request->input('price_neto');
        $products->iva = $request->input('iva');
        $products->price_total = $request->input('price_total');

        $products->save();

        return response()->json([
            'error' => false,
            'products'  => $products,
        ], 200);
    }

我已经搜索过,但仍然找不到解决方案。

product.blade.php

@foreach ($product as $products)
<tr>
  <td>{{$products->id}}</td>
  <td>{{$products->name}}</td>
  <td>{{$products->category_id}}</td>
  <td>{{$products->description}}</td>
  <td>{{$products->price_neto}}</td>
  <td>{{$products->iva}}</td>
  <td>{{$products->price_total}}</td>

    <div class="form-button-action">
      <a onclick="event.preventDefault();editProductForm({{$products->id}});" href="#" class="edit open-modal" data-toggle="modal" value="{{$products->id}}"><i class="material-icons" data-toggle="tooltip" title="Editar">&#xE254;</i></a>
      <a onclick="event.preventDefault();deleteProductForm({{$products->id}});" href="#" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Eliminar">&#xE872;</i></a>
    </div>
  </td>
  </tr>
@endforeach

路线

这些是我的路线。

Route::group(['prefix' => 'product'], function () {
        Route::get('/{id}', [
            'uses' => 'ProductController@show',
            'as'   => 'product.show',
        ]);

        Route::post('/', [
            'uses' => 'ProductController@store',
            'as'   => 'product.store',
        ]);

        Route::put('/{id}', [
            'uses' => 'ProductController@update',
            'as'   => 'product.update',
        ]);

        Route::delete('/{id}', [
            'uses' => 'ProductController@destroy',
            'as'   => 'product.destroy',
        ]);
    });

Product.js

这就是我的模型按下编辑按钮的方式

$("#btn-edit").click(function() {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            type: 'PUT',
            url: '/product/' + $("#frmEditProduct input[name=product_id]").val(),
            data: {
                name: $("#frmEditProduct input[name=name]").val(),
                category_id: $("#frmEditProduct select[name=category_id]").val(),
                description: $("#frmEditProduct input[name=description]").val(),
                price_neto: $("#frmEditProduct input[name=price_neto]").val(),
                iva: $("#frmEditProduct input[name=iva]").val(),
                price_total: $("#frmEditProduct input[name=price_total]").val(),
                image: $("#frmEditProduct input[name=image]").val(),
            },
            dataType: 'json',
            success: function(data) {
                $('#frmEditProduct').trigger("reset");
                $("#frmEditProduct .close").click();
                window.location.reload();
            },
            error: function(data) {
                var errors = $.parseJSON(data.responseText);
                $('#edit-product-errors').html('');
                $.each(errors.messages, function(key, value) {
                    $('#edit-product-errors').append('<li>' + value + '</li>');
                });
                $("#edit-error-bag").show();
            }
        });
    });

An image on the project when I press Edit button

function editProductForm(product_id) {
    $.ajax({
        type: 'GET',
        url: '/product/' + product_id,
        success: function(data) {
            $("#edit-error-bag").hide();
            $("#frmEditProduct input[name=name]").val(data.products.name);
            $("#frmEditProduct select[name=category_id]").val(data.products.category_id);
            $("#frmEditProduct input[name=description]").val(data.products.description);
            $("#frmEditProduct input[name=price_neto]").val(data.products.price_neto);
            $("#frmEditProduct input[name=iva]").val(data.products.iva);
            $("#frmEditProduct input[name=price_total]").val(data.products.price_total);
            $('#editProductModal').modal('show');
        },
        error: function(data) {
            console.log(data);
        }
    });
}

【问题讨论】:

  • find($id) 将返回 null 如果未找到具有给定 ID 的记录。检查id是否正确,如果不存在该id的记录,也可以使用findOrFail($id)抛出异常
  • 如果你dd($products)结果如何?
  • 你能分享一下迁移吗
  • findOrFail($id) 抛出“没有模型 [App\Product] 0 的查询结果”。我使用相同的 id 来删除它,它可以工作。 @porloscerrosΨ
  • Schema::create('products', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table-> unsignedBigInteger('category_id'); $table->string('description'); $table->decimal('price_neto', 10, 2); $table->decimal('iva', 10, 2); $table ->decimal('price_total', 10, 2); $table->timestamps(); }); @SherazKhan

标签: javascript php ajax laravel


【解决方案1】:

您没有将产品 id 的值分配给您从中获取它以发送 put 请求的输入:

function editProductForm(product_id) {
    $.ajax({
        type: 'GET',
        url: '/product/' + product_id,
        success: function(data) {
            $("#edit-error-bag").hide();

            $("#frmEditProduct input[name=product_id]").val(product_id) // <- assign the new value here!!!

            $("#frmEditProduct input[name=name]").val(data.products.name);
            $("#frmEditProduct select[name=category_id]").val(data.products.category_id);
            $("#frmEditProduct input[name=description]").val(data.products.description);
            $("#frmEditProduct input[name=price_neto]").val(data.products.price_neto);
            $("#frmEditProduct input[name=iva]").val(data.products.iva);
            $("#frmEditProduct input[name=price_total]").val(data.products.price_total);
            $('#editProductModal').modal('show');
        },
        error: function(data) {
            console.log(data);
        }
    });
}

然后你可以让它为 put 请求构建 ajax url:

$("#btn-edit").click(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'PUT',

        url: '/product/' + $("#frmEditProduct input[name=product_id]").val(),  // <- here you get the input value!!!

        data: {
            name: $("#frmEditProduct input[name=name]").val(),
            category_id: $("#frmEditProduct select[name=category_id]").val(),
            description: $("#frmEditProduct input[name=description]").val(),
            price_neto: $("#frmEditProduct input[name=price_neto]").val(),
            iva: $("#frmEditProduct input[name=iva]").val(),
            price_total: $("#frmEditProduct input[name=price_total]").val(),
            image: $("#frmEditProduct input[name=image]").val(),
        },
        dataType: 'json',
        success: function(data) {
            $('#frmEditProduct').trigger("reset");
            $("#frmEditProduct .close").click();
            window.location.reload();
        },
        error: function(data) {
            var errors = $.parseJSON(data.responseText);
            $('#edit-product-errors').html('');
            $.each(errors.messages, function(key, value) {
                $('#edit-product-errors').append('<li>' + value + '</li>');
            });
            $("#edit-error-bag").show();
        }
    });
});

【讨论】:

  • 谢谢!是的,事情就是这样发生的。我忘记了我的 product_id 并且在我的控制器中我只需将 $products-&gt;category_id = $request-&gt;select('category_id') 更改为 $products-&gt;category_id = $request-&gt;input('category_id')
  • 太棒了!很高兴知道你解决了它。我错过了控制器,是的,您可以使用该语法或仅使用 $request-&gt;category_id
  • 非常感谢朋友,我很感激。你救了我。
【解决方案2】:

查询返回空值时发生此错误。

你可以试试这样的:

public function update(Request $request, $id)
{
    $products = Product::find($id);

    if($products instanceof Product){
        $products->name = $request->input('name');
        $products->category_id = $request->select('category_id');
        $products->description = $request->input('description');
        $products->price_neto = $request->input('price_neto');
        $products->iva = $request->input('iva');
        $products->price_total = $request->input('price_total');

        $products->save();

        return response()->json([
            'error' => false,
            'products'  => $products,
        ], 200);
    }
    return response()->json([
        'error' => true,
        'message'  => 'Product not found.',
    ], 404);
}

【讨论】:

  • 是的,会抛出“找不到产品。”。 @akshaypjoshi
  • 因为产品在您的表中没有可用的 $id 您正在传入控制器。
猜你喜欢
  • 1970-01-01
  • 2017-11-29
  • 2018-07-18
  • 2019-03-14
  • 1970-01-01
  • 2021-05-22
  • 2016-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多