Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request validation allways passes on Laravel using Dingo/Api

I'm using dingo/api package.

Controller:

public function register(RegisterUserRequest $request)
{
    dd('a');
}

And for example the email field is required:

<?php namespace App\Http\Requests;


class RegisterUserRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email' => 'required'
        ];
    }
}

So I send a request without the email, and still getting the "a" response.

I also tried to extend Dingo\Api\Http\Request instead of App\Http\Request, but still the same.

like image 474
HTMHell Avatar asked Feb 12 '26 10:02

HTMHell


1 Answers

For Dingo to work at all with the FormRequest, by experience (and from this Issue), you have to use Dingo's Form request i.e Dingo\Api\Http\FormRequest; , so you'll have something similar to:

<?
namespace App\Http\Requests;
use Dingo\Api\Http\FormRequest;
use Symfony\Component\HttpKernel\Exception\HttpException;


class RegisterUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
     public function rules()
     {
        return [
            'email' => 'required'
        ];
     }
    // In case you need to customize the authorization response
    // although it should give a general '403 Forbidden' error message
    /**
     * Handle a failed authorization attempt.
     *
     * @return mixed
     */
     protected function failedAuthorization()
     {
         if ($this->container['request'] instanceof \Dingo\Api\Http\Request) {
            throw new HttpException(403, 'You cannot access this resource'); //not a user?
         }

     }
}

PS: This is tested on Laravel 5.2.*

Hope it helps :)

like image 119
Oluwatobi Samuel Omisakin Avatar answered Feb 14 '26 23:02

Oluwatobi Samuel Omisakin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!