【问题标题】:Laravel 5.7 REST api , update section errorLaravel 5.7 REST api,更新部分错误
【发布时间】:2019-04-28 17:47:29
【问题描述】:

Create,Delete,Show 部分也可以正常工作。不知道有什么问题。

这是我的请求(当我调用资源路由的PUT 时):

============
Request body
============
name: John doe
detail: An insteresting detail
type: A fancy type

===============
Request Headers
===============
Accept: application/json
Authorization: Bearer my_secret_token

错误

"message": "没有模型 [App\Product] 的查询结果。"

API\控制器

public function update(Request $request, Product $product)
{
    $input = $request->all();


    $validator = Validator::make($input, [
        'name' => 'required',
        'detail' => 'required'
    ]);


    if($validator->fails()){
        return $this->sendError('Validation Error.', $validator->errors());       
    }


    $product->name = $input['name'];
    $product->detail = $input['detail'];
    $product->save();


    return $this->sendResponse($product->toArray(), 'Product updated successfully.');
}

【问题讨论】:

  • 您需要先find 您的产品,然后再尝试更新它。
  • $product = Product::findOrFail($id); 吗?
  • 我添加了一个anwser,没错。
  • 他不必找到它,因为他将模型作为第二个参数注入!
  • @Matt 我们不知道它是否已从问题中显示的代码中正确注入。

标签: laravel api eloquent


【解决方案1】:

如果您使用的是路由模型绑定(看起来),请务必使用正确的端点来更新您的资源:

PUT /products/{product}
// so this means, for example:
PUT /products/3

然后,Laravel 会自动查找 id 为 3 的 Product。

public function update(Request $request, Product $product) // <-- here is injected.
{
    // the rest of your code..
}

另一种选择是手动查找资源。如果你的路线是这样的:

PUT /products/{id}

如果您想轻松管理响应,请按以下方式查找:

public function update(Request $request)
{
    // find it
    $product = Product::find($request->get('id'));

    // check if exists
    if (! $product)
    {
        return response()->json(['errors' => 'This product does not exist, dude!'], 404);
    }

    // the rest of your code..
}

或者像这样抛出异常:

public function update(Request $request)
{
    // find it
    $product = Product::findOrFail($request->get('id'));

    // the rest of your code..
}

【讨论】:

  • 你在评论// &lt;-- here is injected.没有注入产品的地方。
  • @adam,是的,一个错字,我复制了前一个块。我会更新的。谢谢!
【解决方案2】:

进入你项目所在的文件夹

cd /laravel/your/path_of/api_project

并执行以下命令

php artisan route:list

您将拥有一个完整的表格,其中包含要使用的方法的名称及其 url 以及要使用的每个方法(POST、GET、...)

输出示例----

| PUT|PATCH | api/companys/{company}|  companys.update| App\Http\Controllers\CompanysController@update|

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 1970-01-01
    • 2014-10-27
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    相关资源
    最近更新 更多