How To Upload Files In Laravel 11 Application

To upload files in Laravel, you can utilize Laravel’s built-in file storage capabilities, which make handling file uploads a breeze. Here’s a comprehensive guide on how to upload files in Laravel :

  1. Set Up Your Form: Start by creating a form in your Laravel application to allow users to upload files. Use the HTML <form> tag with the enctype attribute set to multipart/form-data to handle file uploads.
   <form action="{{ route('upload.file') }}" method="POST" enctype="multipart/form-data">
       @csrf
       <input type="file" name="file">
       <button type="submit">Upload</button>
   </form>
  1. Create a Route: Define a route that points to the controller method responsible for handling the file upload.
   Route::post('/upload', 'FileController@upload')->name('upload.file');
  1. Controller Method: In your controller, create a method to handle the file upload. You can use the store() method of the UploadedFile class to move the uploaded file to a storage location.
   use Illuminate\Http\Request;

   class FileController extends Controller
   {
       public function upload(Request $request)
       {
           if ($request->hasFile('file')) {
               $file = $request->file('file');
               $fileName = time() . '_' . $file->getClientOriginalName();
               $file->storeAs('uploads', $fileName); // Store file in storage/app/uploads folder
               // You can also store file in public directory if needed
               // $file->move(public_path('uploads'), $fileName);
               return 'File uploaded successfully.';
           }
           return 'No file uploaded.';
       }
   }
  1. Handle File Storage: Laravel provides multiple storage options including local, S3, and more. You can configure your storage options in config/filesystems.php.
  2. Validation: Don’t forget to validate uploaded files to ensure they meet your requirements. You can use Laravel’s validation rules to validate file size, mime type, and more.
   $request->validate([
       'file' => 'required|file|mimes:jpeg,png,pdf|max:2048', // Example validation rules
   ]);
  1. Display Errors: If there are any errors during file upload or validation, you should display them back to the user for feedback.
   @error('file')
       <div class="alert alert-danger">{{ $message }}</div>
   @enderror

By following these steps, you can easily implement file uploads in Laravel , providing a seamless experience for your users.

Leave a Reply