9951 explained code solutions for 126 technologies


php-laravelHow do I upload a file using PHP Laravel?


The following steps explain how to upload a file using PHP Laravel:

  1. Create a form in your view file with an input type of file.
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="upload_file" />
    <input type="submit" value="Upload File" />
</form>
  1. Create a route in your routes file to handle the form submission.
Route::post('/upload', function() {
    // Handle the form submission
});
  1. Inside the route, you can use the request() helper to get the file from the form submission.
$file = request()->file('upload_file');
  1. Use the store() method to store the file in the desired location.
$file->store('uploads');
  1. You can also use the storeAs() method to store the file with a custom name.
$file->storeAs('uploads', 'custom_name.jpg');
  1. Finally, you can also use the move() method to move the file to a different location.
$file->move('/path/to/destination', 'custom_name.jpg');
  1. You can also use the validate() method to validate the uploaded file before storing it.
$this->validate(request(), [
    'upload_file' => 'required|mimes:jpeg,jpg,png|max:2048'
]);

Helpful links

Edit this code on GitHub