laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.39k stars 10.98k forks source link

The Illuminate\Database\Eloquent\Builder namespace for custom Unique Rule in validations is wrong. #46562

Closed matheusbrdev closed 1 year ago

matheusbrdev commented 1 year ago

Description:

I try to use the Unique Rule in validations:

use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\Database\Eloquent\Builder;

 public function update(Request $request, $id)
    {
        try {
                $rules = [
                    'email' => [
                        'required',
                         Rule::unique('email')
                            ->where(fn (Builder $query) => $query->where('customer_id, '<>', $id))
                     ]
                  ];

                $request->validate($rules);
            } catch (ValidationException $exception) {
                Log::channel('single')->info("validation_error", $exception->getMessage());
        }
    }

But i this exception is throw: Argument #1 ($query) must be of type Illuminate\\Database\\Eloquent\\Builder, Illuminate\\Database\\Query\\Builder given, called in /var/www/html/vendor/laravel/framework/src/Illuminate/Validation/DatabasePresenceVerifier.php on line 85

But if you change to this:

use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;

 public function update(Request $request, $id)
    {
        try {
                $rules = [
                    'email' => [
                        'required',
                         Rule::unique('email')
                            ->where(fn (\Illuminate\Database\Query\Builder $query) => $query->where('customer_id, '<>', $id))
                     ]
                  ];

                $request->validate($rules);
            } catch (ValidationException $exception) {
                Log::channel('single')->info("validation_error", $exception->getMessage());
        }
    }

It's work!. The Illuminate\Database\Query\Builder namespace was shown like a wrong, but it's actually the correct one!

Steps To Reproduce:

  1. Create array for rules;
  2. Read the documentation about custom Unique Rules;
  3. Write a custom unique rule with Rule::unique()->where() method;
driesvints commented 1 year ago

I'm not entirely sure what the issue here is? You indeed need to reference the correct namespace.

matheusbrdev commented 1 year ago

Yes, need. But the namespace was shown like a correct... it's the wrong!

matheusbrdev commented 1 year ago

I need open another issue? Because you closed that

prabodhana commented 7 months ago

@matheusbrdev yes your right. I faced the same issue "Illuminate\Database\Query\Builder" works fine.