Laravel 5 API: ошибка обновления записи

Поэтому я работаю с Laravel 5.2 API и работаю над созданием метода обновления для конкретной Модели. До сих пор методы index, show ($ id) и store работают нормально. Однако я получаю следующую ошибку в моей реализации метода обновления:

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

Вот подробное сообщение об ошибке при попытке использовать PUT на этой конечной точке api / v1 / zone / 1? Description = Blah

Метод сохранения не существует.

0

Решение

Когда вы используете get() метод вы получаете Collection объект. Вы должны использовать first() метод для получения объекта модели.

Узнайте больше здесь: https://laravel.com/docs/5.2/eloquent#retrieving-single-models

2

Другие решения

Вы должны получить один экземпляр модели Zone с помощью first (), затем вы можете использовать методы 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);
}
1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector