Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom Request Rule Returns Unauthorized

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading