Search This Blog

Thursday, September 8

Laravel: Transform Request to custom validation request

Laravel: Transform Request to custom validation request

we can convert any request to any other request, as long as it extends from Illuminate\Http\Request.

There are basically two methods Laravel uses to convert one request to another. The problem here is that it will never get a validation object or trigger the validation automatically, as part of the injection when MyRequest  was passed as an argument. It might also miss a message bag and the error handler, but nothing you can fix by initializing the request just like Laravel does when injecting it.

So you still have to trigger all the sequences the FormRequest (if it extends FromRequest rather than Request) normally does when booting the trait, but still, it's entirely possible and with some little extra work, you could convert any request to any other request.

For example; I'm using this setup to call just one route profile/{section}/save for saving my profile settings. Depending on $section's value, I convert the given $Request to any of my custom form requests for that particular $section.

use App\Http\Requests\MyRequest;

use Illuminate\Http\Request;

...

public function someControllerMethod(Request $Request) {

   $MyRequest = MyRequest::createFrom($Request);

   // .. or

   $MyRequest = MyRequest::createFromBase($Request);

}

...

So to get people started with using a FormRequest as an example, it basically comes to this.

Instead of extending all your custom requests from the default Illuminate\Foundation\Http\FormRequest, use a base class that extends from FormRequest and add a custom method to transform and boot the request as if it were passed as an argument.

namespace App\Http\Requests;

use Illuminate\Routing\Redirector;

use Illuminate\Foundation\Http\FormRequest;

class BaseFormRequest extends FormRequest {

   public function convertRequest(string $request_class) : BaseFormRequest {

      $Request = $request_class::createFrom($this);

      $app = app();

      $Request

        ->setContainer($app)

        ->setRedirector($app->make(Redirector::class));

      $Request->prepareForValidation();

      $Request->getValidatorInstance();

      return $Request;

   }

    public function authorize() {

        return true;

    }

    public function rules() {

        return [];

    }

}

Let all your custom FormRequest extend your BaseFormRequest

namespace App\Http\Requests;


class MyRequest extends BaseFormRequest {

  ...

}

Now anywhere you want to convert a request, use the base class in your controller method and convert it using convertRequest with the custom request class you wish to convert.

public function someControllerMethod(BaseFormRequest $Request) {

  $MyRequest = $Request->convertRequest(MyRequest::class);

}

No comments:

Post a Comment