Search code examples
phplaravelapivalidationroutes

How to validate by default a parameter in a laravel api route


A question has arisen. Suppose I have an api route that is

get: api/v1/conferences/{conference_id}/languages

The purpose would be to get the languages linked to this conference. My program, almost always starts with conferences/{conference_id} so the conference_id must always be real. In case the conference_id does not exist, I should throw an exception.

I want to do this without putting any logic in the controllers or any class that has any particular logic of mine. I would like it to be validated by default from the laravel kernel, is that possible?

I mean, i want that every time somebody access to a route which starts with conferences/{conference_id} the program would be able to check if this id is real

Thanks


Solution

  • Use exists in validation rules like:

    <?php
    
    namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    
    class ConferencesRequest extends FormRequest
    {
        /**
         * @inheritDoc
         */
        public function all($keys = null)
        {
            $data = parent::all();
            $data['conference_id'] = $this->route('conference_id');
    
            return $data;
        }
    
        /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules()
        {
            return [
                'conference_id' => ['required', 'integer',  'exists:' . App\Models\Conference::class . ',id'],
            ];
        }
    }
    
    

    Or, if you dont want to use a FormRequest class, use this:

    p.s. param should be changed to conference instead of conference_id:

    use App\Models\Conference;
     
    Route::get('conferences/{conference}/languages', function (Conference $conference) {
        //...
    });
    

    See: https://laravel.com/docs/9.x/routing#route-model-binding