I want to pass the value of the current field to a custom validation function in a Request class in my Laravel project.
I have tried the following:
public function rules()
{
return [
'id'=>'required',
//'type'=>'required|in:Attachment,Audio,Book,Picture,Video',
'type'=>['required', $this->validateFileType()],
//'type'=>[new Enum(FileType::class)], # only available on PHP 8.1
'soft_price' => 'numeric|min:1000',
'hard_price' => 'numeric|min:1000',
];
}
public function validateFileType($type){
$file_types = ['Attachment', 'Audio', 'Book', 'Picture', 'Video'];
if(in_array($type, $file_types))
return true;
else
return false;
}
and I get the following error:
"Too few arguments to function App\\Http\\Requests\\FileUpdateRequest::validateFileType(), 0 passed in C:\\xampp\\htdocs..."
How do I do it?
CodePudding user response:
You should have a look at Custom Validation Rules.
You can add a custom rule Class with artisan:
php artisan make:rule MyFileType
In it, you can access the current value and also output custom error messages
public function passes($attribute, $value)
{
$file_types = ['Attachment', 'Audio', 'Book', 'Picture', 'Video'];
if(in_array($value, $file_types))
return true;
else
return false;
}
You use it in your code like this:
use App\Rules\MyFileType;
public function rules()
{
return [
...
'type' => ['required', new MyFileType],
...
];
}
CodePudding user response:
Create new rule:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class FileTypeRule implements Rule
{
public function passes($attribute, $value)
{
$file_types = ['Attachment', 'Audio', 'Book', 'Picture', 'Video'];
if(in_array($file_types, $value))
return true;
else
return false;
}
}
Use it in the Request Rules method:
public function rules()
{
return [
'id'=>'required',
'type'=>['required', new FileTypeRule()],
'soft_price' => 'numeric|min:1000',
'hard_price' => 'numeric|min:1000',
];
}
CodePudding user response:
You have to pass two arguments in the rules function and for more information please have look laravel documentation