skip to Main Content

I’m developing a laravel api using resource controller. There I have to use PUT method for updating something.

When I try to pass data through body with form-data the validation error happens. I have to pass the data through param.

Is this normal for laravel resource controller? If so why?

Here’s my code.

public function update(RoleRequest $request, string $id)
{
     $data = Role::find($id);

     $new_data = [
         'name' => $request->name
     ];

     $data->update($new_data);

     return $this->apiResponse(true, 'role updated successfully', $data, 200);
}

Here’s the validation error.

{
    "success": false,
    "message": "Validation errors",
    "data": {
        "name": [
            "The name field is required."
        ]
    }
}

2

Answers


  1. the error message is clear, by using RoleRequest, you are validating the parameters entered in the request before it reaches the rest of the function. This is very useful to ensure that the fields that are required arrive.

    You can go into RoleRequest and see that you have the field name as required. That means that the failure is due to not having sent that parameter in the request of your call.

    Login or Signup to reply.
  2. I’ve copied my comment to this answer so I can add more information.

    I don’t think Laravel still has the problem described in the answer Lua linked to – that was six years ago. I use POST, PATCH, and PUT in Laravel without an issue.

    When you send data in the body and have validation rules defined in the request object, those validation rules are applied. If you wrote the validation to require the name why are you surprised the validation fails if you don’t supply that attribute? If you want different validation rules for PUT or PATCH, use a different Request class.

    However, I don’t think you should be using PUT to update your resource. The semantic of a PUT action is to replace the resource with the data provided.

    If the validation of a POST request is to require the name attribute, why would you not require it if you are replacing the resource?

    Use PATCH when you only want a partial update and write a new RoleUpdateRequest class to validate fields only when they are present.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search