PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 30, 2022

[FIXED] Validation - file name required if file upload has file

 January 30, 2022     eloquent, laravel, laravel-5, php, validation     No comments   

Issue

im having a form controller for an inventory, where people can add items and add bills, manuals etc too while creating the items. My problem is, that i want to get a file name too (e.g. Bill for the uploaded file) but i only want to require it, if they really have a file chosen in the form.

my code right now looks like this:

i tried everything out like required_unless, required_if but nothing works. Maybe i do sth wrong or my idea just doesnt work with this validation rules?

The validation in the Controller:

public function save(Request $request)
    {
        $validatedData = $request->validate([
            'file' => 'nullable|file',
            'files_label' => 'required_unless:file,empty|string',
        ]);

The error message in my html is: files_label has to be a string (so i guess its still required)...

my blade looks like this

<input class="form--textinput" name="files_label" id="files_label" value="{{old('files_label')}}">
<input type="file" class="custom-file" name="file" id="file" value="{{old('file')}}">

How can i make it work that, it just requires the file_label if i chose a file to upload?

UPDATE 1: tried it out with type="text" too. still getting the error: "The files label must be a string."

UPDATE 2: So I deleted the type requirement "string" and now it looks, like it works. he doesnt want the files_label field to be a string. required_unless works now too as it looks like. Can someone tell my why it is like that? Why he wants a string, if the field is not required at all?

code looks like this now:

'file' => 'nullable|file',
'files_label' => 'required_unless:file,',

Solution

I think you need required_with in this case . like this

$validatedData = $request->validate([
                'file' => 'nullable|file',
                'files_label' => 'required_with:file,empty|string',
            ]);

https://laravel.com/docs/5.5/validation#rule-required-with



Answered By - sh1hab
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing