John Davidson

php - Laravel9: route parameter always missing in validation

0 comments
Message:


I am using Laravel v9.2.1 + Laravel Sanctum v2.14.1


I got a route


DELETE /api/v1/auth/tokens/{token}

for example (the token is an uuid)


DELETE http://example.com/api/v1/auth/tokens/5fcfa274-81d8-4e9f-8feb-207db77531af

And I am sure it works as expected via php artisan route:list


Before handling by the Controller, it should be validated by a FormRequest


app/Http/Controllers/V1/Auth/TokensController.php


namespace App\Http\Controllers\V1\Auth;

use App\Http\Requests\V1\Auth\Tokens\{
DestroyRequest,
};

class TokensController extends Controller
{
public function destroy(DestroyRequest $request) {
$request->user()->tokens()->where('id', $request->token)->first()->delete();
return response()->noContent();
}
}

app/Http/Requests/V1/Auth/Tokens/DestroyRequest.php


class DestroyRequest extends FormRequest
{
public function rules()
{
return [
'token' => [
'required',
'string',
'regex:/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
Rule::exists('personal_access_tokens')->where(function ($query) {
return $query->where('tokenable_id', $this->user()->id);
}),
]
];
}
}



But what I only got is The token field is required


I had already pass the token, why the 'required' rule still working?





What I tried


Only if I pass the token parameter like below, it will work


DELETE /api/auth/tokens/something?token=test_regex_is_working


I try to dd($this->token) in app/Http/Requests/V1/Auth/Tokens/DestroyRequest.php, it works as expected.




My Answer:
> In your `DestroyRequest` class, make sure you are properly defining the rules for validating the `token` parameter. Here is an example of how you can do this:

php
namespace App\Http\Requests\V1\Auth\Tokens;

use Illuminate\Foundation\Http\FormRequest;

class DestroyRequest extends FormRequest
{
public function authorize()
{
return true;
}

public function rules()
{
return [
'token' => 'required|uuid', // Add validation rules for the token parameter
];
}
}


By adding the `'token' => 'required|uuid'` rule in the `rules()` method of your `DestroyRequest` class, Laravel will validate that the `token` parameter is present in the request and is a valid UUID before allowing the request to be processed by the controller.

Make sure to also import the necessary classes in your `DestroyRequest` class, such as `use Illuminate\Foundation\Http\FormRequest;` and any other classes that may be needed for validation.

After making these changes, try sending a DELETE request to your endpoint with the `token` parameter included, and Laravel should now properly validate the request before passing it to the controller.

Rate this post

3 of 5 based on 7453 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us