How to upload files to laravel? Already tried a bunch of different ways, not in what does not work. There is a html code

<form method="post" action=""> <input type="file" name="image"> <button type="submit">Отп</button> </form> 

and controller code

 if($request->image!= '') { $set->image= $request->image; File::put($request->image, $request->image); } 

Where is my mistake? Direct on the right path. Thank.

  • Before asking this question, I carefully reviewed the documentation. - asd
  • And still it is not clear how it is done, I tried through Storage, but an empty file is created. - asd
  • And where did you get this code from the documentation? What is the $set variable? The documentation does not explicitly use this check: $request->image!= '' . - VenZell
  • one
    this is missing <form method="post" enctype="multipart/form-data"> - apelsinka223

3 answers 3

enctype="multipart/form-data" must be added to the enctype="multipart/form-data" to allow file uploads.

 <form method="post" action="" enctype="multipart/form-data"> <input type="file" name="image"> <button type="submit">Отп</button> </form> 

Next, create a controller:

 public function fileUpload(Request $request){ if($request->isMethod('post')){ if($request->hasFile('image')) { $file = $request->file('image'); $file->move(public_path() . '/path','filename.img'); } } } 

Where

  • $ request-> hasFile ('image') `- check for the existence of a file, specify the field identifier as an argument
  • $file = $request->file('image') - write file object to variable
  • $file-move(public_path() . '/path','filename.img') is a method for moving a file to the directory we need, the 1st argument specifies the directory in which to save the file, the 2nd indicates the new file name
  • public_path() - will return us the full path to the public directory

    You all say right in the comments. The documentation is all written in detail. But judging by what you wrote in the example, you should start by learning the basics of PHP itself. Where did you get the image field in the Request class? Where did you find this? The documentation in black on white says $file = $request->file('image'); What is the $set variable? But your code is supposed to break even before reaching it. It will not hurt you to learn how to view logs in Laravel, and indeed how to debug PHP applications. At least with the usual var_dump() for a start. In general, it's too early for you in Laravel. At a minimum, read the documentation carefully and understand what is written there.

      There is a ready implementation for those who use Laravel. The package is called UploadImage. There is an article in Russian: Flexible loading of images in Laravel