Yes, you can have a constructor in a Form Request. You can override the __construct method in your Form Request class and pass in any dependencies you need. Here's an example:
use Illuminate\Foundation\Http\FormRequest;
class MyFormRequest extends FormRequest
{
protected $dataFromDb;
public function __construct(DataRepository $dataRepository)
{
$this->dataFromDb = $dataRepository->getData();
}
public function rules()
{
return [
'field1' => [new CustomRule1($this->dataFromDb)],
'field2' => [new CustomRule2($this->dataFromDb)],
'field3' => [new CustomRule3($this->dataFromDb)],
];
}
}
In this example, we're injecting a DataRepository into the constructor of our MyFormRequest class. We then use this repository to fetch the data we need from the database and store it in a property on the class. We can then use this property in our rules method to pass the data to our custom validation rules.
Note that you'll need to update the use statement at the top of your file to import the FormRequest class from the correct namespace.