Skip to content
Advertisement

PHP/Laravel FormRequests Types

I have a doubt about the FormRequest Class (I think it apply at other classes).

I have a class which has a method init(). This method receive a VehicleRequest. I’m going to share a simplified version of the code:

public function init(VehicleRequest $request){
 if($request->input('type' == 'car'){
    $vehicle = new Car($request);
 } else {
    $vehicle = new MotorCycle($request);
 }
}

The class Car:

class Car{

  public function __construct(VehicleRequest $request){
    ...
  }

}

The request I send (in car case) looks like:

{
  "type": car,
  "wheels": 4,
  "brand": bmw
}

Now, in this example a Car class is initialized with the VehicleRequest. But I need to do another checks in addition to those made by VehicleRequest. For example, I need to check if the wheels are 4, the brand is in a set I define…

So, how can I do the Car class wait as parameter a CarRequest?

For example instead a VehicleRequest? Example:

class Car{

  public function __construct(CarRequest $request){
    ...
  }

}

I hope you undestand my doubt, thanks!

Advertisement

Answer

Use the service container here:

enter the following in the AppServiceProvider

public function register ()
{

  $type = app(Request::class)->get('type')

  if($type == 'car') {
    $this->app->bind(VehicleRequestInterface::class, CarRequest::class)
  } else {
    $this->app->bind(VehicleRequestInterface::class, VehicleRequest::class)
  }
}


class Car {

  public function __construct(VehicleRequestInterface $request){
    ...
  }

}

class CarRequest extends FormRequest implements VehicleRequestInterface {
 ....
}

class VehicleRequest extends FormRequest implements VehicleRequestInterface {
 ....
}

// VehicleRequestInterface

interface VehicleRequestInterface 
{
}

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement