Step 1: Create a View for File Upload
Create a new view file resources/views/uploadfile.blade.php. In this file, we will create a simple form to allow users to upload a file.
Step 2: Create a Controller to Handle File Uploads
Run the following Artisan command to create a new controller:
This will generate a controller UploadFileController.php in the app/Http/Controllers directory. Now, edit this file to handle file uploads.
Step 3: Define Routes
Now, define the routes to show the form and handle the file upload. Add the following code to your routes/web.php file:
Step 4: Create a Directory to Store Files
Make sure to create an uploads directory in your project's public folder to store the uploaded files. You can create the directory manually, or Laravel will create it automatically when you move a file. However, ensure the directory is writable by your web server.
Ensure the correct permissions for the directory:
Step 5: Test the File Upload
To test the file upload functionality, visit the following URL in your browser:
You should see a file upload form. When you select a file and submit the form, the file will be uploaded, and you should see the file details printed on the screen. The file will be saved in the public/uploads directory.
Step 6: Add Success/Error Messages (Optional)
To enhance the user experience, you can add success and error messages. In the uploadfile.blade.php view, add the following code to display messages:
This will display a success message after a successful upload and an error message if something goes wrong.
Conclusion
With these steps, you now have a working file upload functionality in Laravel. The user can upload a file via a form, and the file will be stored on the server in the public/uploads directory.
