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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 
{
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x