I am creating a simple API to check the requests rules. It always returns 403 unauthorized.
Firstly, I run php artisan make:request TestRequest then it will generate two functions, authorize() and rules().
This is my TestRequest:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TestRequest extends FormRequest {
public function authorize() {
return false;
}
public function rules() {
return [
'platform' => ['nullable', 'string'],
'username' => ['nullable', 'string'],
'phone_number' => ['nullable', 'string'],
'phone_number' => ['nullable', 'string'],
'type' => ['nullable', 'integer'],
'gender' => ['nullable', 'string'],
'status' => ['nullable', 'string'],
'label_id' => ['nullable', 'array'],
'label_id.*' => ['integer'],
'interest' => ['nullable', 'string'],
'sentiment_id' => ['nullable', 'integer'],
'phone_code' => ['nullable', 'string'],
'channel' => ['nullable', 'string'],
'age_id' => ['nullable', 'integer'],
'limit' => ['nullable', 'string'],
'page' => ['nullable', 'integer'],
'per_page' => ['nullable', 'integer']
];
}
}
Then, my routes/api.php:
<?php
use Illuminate\Support\Facades\Route;
Route::get('test', \App\Http\Controllers\api\TestController::class);
Then my TestController.php
<?php
use App\Http\Controllers\Controller;
use App\Http\Requests\TestRequest;
class TestController extends Controller {
public function __invoke(TestRequest $request) {
$valid_request = $request->validated();
return $valid_request;
}
}
Those returns this
{
"status": "error",
"message": "This action is unauthorized."
}
>Solution :
modify the authorize() method to return true
public function authorize() {
return true;
}