Skip to content
Advertisement

How to get file input name in Laravel?

I am using a jQuery form builder to create any kind of form input. The issue I had, in particular, is when I create multiple file inputs, the input name is generated randomly by default, the format is something like “file-0000-0”. I would like to get the input name but since it’s random, I can only think of one way to fetch the name which is by using the allFiles() method. How do I fetch the name of the input?

Code Example

$fileRequest = $request->allFiles();

return $fileRequest;

It will return something like this:

{file-1649657296668-0: {…}, file-1649657297967-0: {…}}.

Now how do I get both of the file input names above? Thanks for the help.

Advertisement

Answer

Since allFiles() returns associative array you can get keys:

$files = $request->allFiles();
$name_of_files = array_keys($files);
// ["file-1649657296668-0", "file-1649657297967-0"]

Or you can loop through that array and access files as well:

$files = $request->allFiles();
foreach($files as $name_of_file => $file)  {
  echo $name_of_file; // file-1649657296668-0
  // $file is UploadedFile instance
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement