Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters in Laravel Rule?

Tags:

laravel

I would like to move this code to the App\Rule:

//Currently in class AppServiceProvider extends ServiceProvider

Validator::extend('empty_if', function ($attribute, $value, $parameters, $validator) {
   return ($value != '' && request($parameters[0]) != '') ? false : true;
});

So that it should be this:

//in: App\Rules\EmptyIf

public function passes($attribute, $value, $parameters)
{
   return ($value != '' && request($parameters[0]) != '') ? false : true;
}

But my problem is, that I cannot pass $parameters with

Validator::extend('empty_if', 'App\Rules\EmptyIf@passes');

How would you pass parameters to Laravel Rule?

like image 284
Philipp Mochine Avatar asked May 04 '18 11:05

Philipp Mochine


People also ask

How to pass parameter to rule in Laravel?

You can access the passed param in the Rule's constructor, so just set a globally scoped variable and now you can reference it inside of the passes() method. You could even use the same approach to have the value in the validator message. Save this answer.

What is the method used to configure validation rules in form request?

Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.


2 Answers

Here is a simpler and updated way of accomplishing this, without extending the validator. You can access the passed param in the Rule's constructor, so just set a globally scoped variable and now you can reference it inside of the passes() method. You could even use the same approach to have the value in the validator message.

The validate call:

case 'measurement':
 $request->validate([
   'updates.*.value' => [
   new Measurement('foo-bar'),
   ],
 ]);
 break;

The Rule:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Measurement implements Rule
{
/**
 * Create a new rule instance.
 *
 * @param $param
 */
public function __construct($param)
{
    $this->type = $param;
}

public $type;
/**
 * Determine if the validation rule passes.
 *
 * @param string $attribute
 * @param mixed $value
 * @param array $parameters
 * @return bool
 */
public function passes($attribute, $value)
{
    dd($this->type, 'params');
    return;
}
like image 81
Nathan Brown Avatar answered Oct 09 '22 07:10

Nathan Brown


You can pass parameters with constructor in Rule

public function __construct($params)
{
    $this->params = $params;
}

Then access parameters in passes method

public function passes($attribute, $value)
{
  //access params with $this->params
}
like image 26
Lilit Aghayan Avatar answered Oct 09 '22 08:10

Lilit Aghayan