Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 File Upload Tutorial

Last Updated on April 5, 2024 by

In this short example tutorial, I will show you how to upload a file to a laravel 11 application and store it in a folder.

Let’s get started by following the steps below:

Step 1 – Create Form View

Create a form where users select file for upload to server:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 11 File Upload Tutorial - itcodStuff.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}"> <!-- Add this line to include CSRF token -->
</head>
<body>
    <form action="{{ url('upload-file') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <input type="file" name="file" id="file">
        <button type="submit">Upload</button>
    </form>
</body>
</html>

Step 2- Create Controller and Handle File Upload

Create a methods in controller file to handle file upload process:


    public function index()
    {
        return view('upload');
    }

    public function uploadFile(Request $request)
    {
        $request->validate([
            'file' => 'required|file|mimes:jpeg,png,pdf|max:2048', // Example validation rules
        ]);

        if ($request->file('file')->isValid()) {
            $file = $request->file('file');
            $fileName = time() . '_' . $file->getClientOriginalName();
            $filePath = $file->storeAs('uploads', $fileName); // Store file in storage/app/uploads

            // Optionally, you can store the file path in the database or perform other actions here

            return redirect()->back()->with('success', 'File uploaded successfully.');
        }

        return redirect()->back()->with('error', 'File upload failed.');
    }

Step 3 – Add Routes

Add routes in web.php file to handle file upload requests:

use App\Http\Controllers\UploadFileController;

Route::get('/file-form', [UploadFileController::class, 'showForm']);
Route::post('/upload-file', [UploadFileController::class, 'uploadFile']);

Step 4 – Display Success/Error Messages in View

Edit your upload.blade.php and add the following line into it to display success or error messages after the form submission:

@if(session('success'))
    <div>{{ session('success') }}</div>
@endif

@if(session('error'))
    <div>{{ session('error') }}</div>
@endif

Step 5 – Test Application

Run application by using the following command:

php artisan serve

Now test your laravel 11 file upload application in browser:

http://127.0.0.1:8000/file-form

With just 5 steps you will be able to easily upload the file in Laravel 11 application.

Leave a Comment