Reputation: 1046
How to check if a file should be uploaded in a form validation request ?
This is what I have so far:
class UpdateRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$rules = [
'title' => 'required',
'content' => 'required',
];
if ($this->request->hasFile('image') && $this->request->file('image')->isValid()) {
$rules['image'] = 'image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000';
}
return $rules;
}
}
but I get this error:
Call to undefined method Symfony\Component\HttpFoundation\InputBag::hasFile()
What can I do ?
Upvotes: 0
Views: 1934
Reputation: 6341
You can use nullable validation rules. So all the validations will be applied only if the value is not null
public function rules()
{
$rules['title'] = ['required'];
$rules['content'] = ['required'];
$rules['image'] = ['nullable', 'image','mimes:jpg,png,jpeg,gif,svg','max:2048','dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000'];
return $rules;
}
Upvotes: 1
Reputation: 35180
The reason you're getting this error is because you're trying to call hasFile
on the underlying request
property. Since FormRequest
extends the normal Laravel Request
class, you can simply call $this->hasFile()
and $this->file()
:
if ($this->hasFile('image') && $this->file('image')->isValid()) {
$rules['image'] = 'image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000';
}
That being said, it would make more sense to add nullable to the validation rules if the image is optional since image
will be checking to see if it's a valid file or not:
public function rules()
{
return [
'title' => 'required',
'content' => 'required',
'images' => [
'nullable',
'image',
'mimes:jpg,png,jpeg,gif,svg',
'max:2048',
'dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000',
],
];
}
Upvotes: 1
Reputation: 12391
you can use request()
helper class to get request
your code should be like this
class UpdateRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$rules = [
'title' => 'required',
'content' => 'required',
];
if (request()->hasFile('image') && request()->file('image')->isValid()) {
$rules['image'] = 'image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000';
}
return $rules;
}
}
here $this
refer to Symfony\Component\HttpFoundation\InputBag
this class which doesn't have hasFile()
function that's why your getting that error
Upvotes: 1