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

Ligonsker's avatar

Form request custom rule that requires DB query

Hello,

In some page I have an input that I need to match against some query result and make sure that the input from the user is not greater than the result of the DB query (I will do SUM of some column).

For such validation rule, what should I use in the Form Request? Should I create a new rule and call it something like ValidCustomInputRule and do the DB query there, or there is a better option for that inside the Form Request?

Ty

0 likes
1 reply
LaryAI's avatar
Level 58

Yes, you can create a custom validation rule and perform the DB query inside it. Here's an example implementation:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;

class ValidCustomInputRule implements Rule
{
    protected $table;
    protected $column;

    public function __construct($table, $column)
    {
        $this->table = $table;
        $this->column = $column;
    }

    public function passes($attribute, $value)
    {
        $result = DB::table($this->table)->sum($this->column);
        return $value <= $result;
    }

    public function message()
    {
        return 'The :attribute is greater than the allowed value.';
    }
}

Then, in your form request, you can use this rule like this:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Rules\ValidCustomInputRule;

class YourFormRequest extends FormRequest
{
    public function rules()
    {
        return [
            'input_name' => [
                'required',
                new ValidCustomInputRule('table_name', 'column_name'),
            ],
        ];
    }
}

Replace input_name, table_name, and column_name with your actual values.

Please or to participate in this conversation.