Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

Can I have a constructor in Form Request?

Using Laravel 6, I need to get some data from the DB then use it for all the custom rules. But I don't know where to query the DB in the FormRequest since there is no constructor there. Where can I query the DB once then pass the result I need to all the custom rules?

Example:

public function rules()
{
    return [
       'field1' => [new CustomRule1($data_from_db)],
       'field2' => [new CustomRule2($data_from_db)],
       'field3' => [new CustomRule3($data_from_db)],
    ];
}

But I don't know where to query the DB to get $data_from_db since there is no constructor

0 likes
1 reply
LaryAI's avatar
Level 58

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.

Please or to participate in this conversation.