Ruka Xing
Ruka Xing

Reputation: 642

Laravel 5.7 REST api , update section error

Create,Delete,Show section is working as well. I don't know what's problem.

This is my request (when I call the PUT of a resource route):

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

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

Error

"message": "No query results for model [App\Product]."

Api\Controller

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

Upvotes: 1

Views: 1237

Answers (2)

Amirouche
Amirouche

Reputation: 3756

Enter in the folder of your project

cd /laravel/your/path_of/api_project

and execute the following command

php artisan route:list

and you will have a complete table that contains the names of the methods to use and their url and each methods to use (POST, GET, ...)

output example ----

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

Upvotes: 1

Kenny Horna
Kenny Horna

Reputation: 14241

If you are using Route Model Binding (as it seems), be sure to use the proper endopoint to update your resource:

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

Then, Laravel will automatically find a Product with the id of 3.

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

The other option is to find the resource manually. If your route is like this:

PUT /products/{id}

Find it like this if you want to manage the response easily:

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..
}

or like this to throw an exception:

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

    // the rest of your code..
}

Upvotes: 2

Related Questions