Laravel 5 API:更新记录错误

时间:2016-04-04 15:36:38

标签: php laravel laravel-5.2 laravel-routing api-design

所以我正在使用Laravel 5.2 API,我正在为特定模型创建更新方法。到目前为止,索引,show($ id)和存储方法工作正常。但是我在更新方法实现上遇到以下错误:

BadMethodCallException in Macroable.php line 81:
Method save does not exist.

以下是更新方法:

public function update($id, CreateZoneRequest $request)
{
    $zones = Zone::where('_id', '=', $id) -> get();

    if(sizeof($zones) == 0){
        return response()->json(['message' =>'That zone number is invalid', 'code' => 404], 404);
    }

    $description = $request->get('description');

    $zones ->description = $description;

    $zones ->save();

    return response() -> json(['message' => 'The zone has been updated'], 200);
}

这是CreateZoneRequest代码:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class CreateZoneRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return 
        [
            'description' => 'required',
        ];
    }

    public function response (array $errors){
        return response() -> json(['message' => 'You are missing a required field', 'code' => 422], 422);
    }
}

这是索引方法(供参考)。这个没有问题:

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Zone;

use Illuminate\Support\Facades\Input;

use App\Http\Requests\CreateZoneRequest;

class ZoneController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $zones = Zone::all();

        if(sizeof($zones) == 0){
            return response()->json(['message' =>'There are no zones', 'code' => 404], 404);
        }

        return response() -> json(['data' => $zones], 200);
    }

尝试在此端点api / v1 / zones / 1上使用PUT时,会出现详细的错误消息吗?description = Blah

Method save does not exist.

2 个答案:

答案 0 :(得分:2)

使用get()方法时,会得到Collection个对象。您应该使用first()方法来获取模型对象。

在此处阅读更多内容:https://laravel.com/docs/5.2/eloquent#retrieving-single-models

答案 1 :(得分:1)

您必须使用first()获取Zone模型的单个实例,然后您可以使用save()或update()方法

public function update($id, CreateZoneRequest $request)
{
    $zones = Zone::where('_id', '=', $id) -> first();

    if(sizeof($zones) == 0){
        return response()->json(['message' =>'That zone number is invalid', 'code' => 404], 404);
    }

    $description = $request->get('description');

    $zones ->description = $description;

    $zones ->save();

    return response() -> json(['message' => 'The zone has been updated'], 200);
}