我正在创建一个简单的 API 来检查请求规则。它总是返回
403 unauthorized
。
首先,我运行
php artisan make:request TestRequest
,然后它将生成两个函数,authorize()
和rules()
。
这是我的
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']
];
}
}
那么,我的
routes/api.php
:
<?php
use Illuminate\Support\Facades\Route;
Route::get('test', \App\Http\Controllers\api\TestController::class);
然后我的
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;
}
}
那些返回这个
{
"status": "error",
"message": "This action is unauthorized."
}
修改authorize()方法返回true
public function authorize() {
return true;
}