0
votes

I create custom Request which named "StoreUser" for custom validation rules for store and update methods. For store method when i using POST method in Postman it's all working good. But for PATCH/PUT method i catch error: "The PATCH method is not supported for this route".

Supported methods: GET, HEAD". My URL for PATCH method: http://127.0.0.1:8000/api/users/44 Using debagger, i found that the problem occurs when custom Request "StoreUser" start return array rules in rules() method. Below my code. Only error occurs in PATCH/PUT method, POST it's ok

ApiResource

Route::apiResource('users', 'UserController');

UserController update/store methods

public function store(StoreUser $request)
{
    $request->validated();

    $password = User::hashPassword($request->get('password'));
    $request->merge(['password' => $password]);

    $user = User::create($request->all());
    return response()->json($user, 201);
}

public function update(StoreUser $request, $id)
{
    $request->validated();
    $user = User::find($id);
    $user->update($request->all());
    return response()->json($user, 200);
}

Custom Request StoreUser

public function rules()
{
    return [ // in this place error occurs ONLY IN PATCH/PUT methods
        'name' => 'required|min:5',
        'email' => 'required|email|unique:users',
        'password' => 'required|min:6|max:50'
    ];
}
2

2 Answers

0
votes

Try to romve $request->validated(); when you use custom valdation class then there is no need to call validated() method

public function update(StoreUser $request, $id)
{
$request->validated();
$user = User::find($id);
$user->update($request->all());
return response()->json($user, 200);
}

use following code
public function update(StoreUser $request, User $user)
{
$user->update($request->all());
return response()->json($user, 200);
}

In above code User $user use as parameter its mean that route model binding so there is no need to use extra query to find user

0
votes

Have you tried adding _method="PATCH" in the body of the request. The type of request should be POST.