Click Below to subscribe

How to Upload Single Or Multiple Files in Laravel

Laravel provides a convenient way to upload files. In this article, we gonna learn how to upload single/multiple files.

1. Let's create a new laravel project.

 composer create-project laravel/laravel laravel-file-upload

2. Create the symbolic link between public and storage/app/public.

php artisan storage:link

3. You may retrieve uploaded files from an Illuminate\Http\Request instance using the file method or using dynamic properties. The file method returns an instance of the Illuminate\Http\UploadedFile class which provides a variety of methods.

Ref:- https://github.com/symfony/symfony/blob/6.0/src/Symfony/Component/HttpFoundation/File/UploadedFile.php

  • getClientOriginalName()
  • getClientOriginalExtension()
  • getClientMimeType()
  • isValid()
  • move()

Also, there is another UploadedFile class that extends symfony's UploadedFile class.

Ref:- https://github.com/laravel/framework/blob/9.x/src/Illuminate/Http/UploadedFile.php

  • store(path)
  • storeAs(path, filename)

Note:- store() method internally uses storeAs() method. store() method automatically generates hash filename for our uploaded file and store it to storage/app directrory.

that's why we need to link the public folder with storage to make files publically accessible.

 

4. Create a controller.

php artisan make:controller UploadController

app/Http/Controllers/UploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UploadController extends Controller
{
    public function index()
    {
        return view('index');
    }

    public function uploadSingle(Request $request)
    {
        if($request->hasFile('file')) {
            $file = $request->file('file');

            if($file->isValid()) {
                $filePath = $file->store('public/uploads');
                $fileName = basename($filePath);

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

    public function uploadMultiple(Request $request)
    {
        if($request->hasFile('files')) {
            $files = $request->file('files');

            foreach ($files as $key => $file) {
                if($file->isValid()) {
                    $filePath = $file->store('public/uploads');
                    $fileName = basename($filePath);
                }
            }
            return redirect()->back()->with('message','File uploaded.');
        }
        return redirect()->back();
    }

    public function uploadSingleCustom(Request $request)
    {
        if($request->hasFile('file')) {
            $file = $request->file('file');

            if($file->isValid()) {
                $destinationPath = public_path('uploads');
                $extension = $file->getClientOriginalExtension();
                $originalName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
                $fileName = $originalName . '-' . uniqid() . '.' . $extension;
                $file->move($destinationPath, $fileName);

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

    public function uploadMultipleCustom(Request $request)
    {
        if($request->hasFile('files')) {
            $files = $request->file('files');

            foreach ($files as $key => $file) {
                if($file->isValid()) {
                    $destinationPath = public_path('uploads');
                    $extension = $file->getClientOriginalExtension();
                    $originalName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
                    $fileName = $originalName . '-' . uniqid() . '.' . $extension;
                    $file->move($destinationPath, $fileName);
                }
            }
            return redirect()->back()->with('message','File uploaded.');
        }
        return redirect()->back();
    }
}

Note:- In the above code store('public/uploads') function stores your file in storage/app/public/uploads directory.

you don't need to create uploads folder manually. (uploadSingle, uploadMultiple)

In the rest two functions (uploadSingleCustom, uploadMultipleCustom) you need to create uploads folder inside public folder.

5. Create a view.

resources/views/index.blade.php

<main>
    <div class="row mb-2">
        <div class="col-sm-8 offset-2">
            @if(Session::has('message'))
            <div class="alert alert-success" role="alert">{{ Session::get('message') }}</div>
            @endif
            <div class="row">
                <div class="col-md-4">
                    <h6>Upload Single</h6>
                </div>
                <div class="col-md-6">
                    <form method="POST" action="{{ url('upload-single') }}" enctype="multipart/form-data">
                        @csrf
                        <div class="input-group">
                            <div class="custom-file">
                                <input type="file" name="file" class="custom-file-input" id="inputFileSingle" required accept="image/*">
                                <label class="custom-file-label" for="inputFileSingle">Choose file</label>
                            </div>
                            <div class="input-group-append">
                                <button type="submit" class="btn btn-primary float-right mr-2">Upload <i class="fa fa-upload"></i></button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div class="row mt-3">
                <div class="col-md-4">
                    <h6>Upload Multiple</h6>
                </div>
                <div class="col-md-6">
                    <form method="POST" action="{{ url('upload-multiple') }}" enctype="multipart/form-data">
                        @csrf
                        <div class="input-group">
                            <div class="custom-file">
                                <input type="file" name="files[]" class="custom-file-input" id="inputFileMultiple" required accept="image/*" multiple>
                                <label class="custom-file-label" for="inputFileMultiple">Choose file</label>
                            </div>
                            <div class="input-group-append">
                                <button type="submit" class="btn btn-primary float-right mr-2">Upload <i class="fa fa-upload"></i></button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div class="row mt-3">
                <div class="col-md-4">
                    <h6>Upload Single Custom</h6>
                </div>
                <div class="col-md-6">
                    <form method="POST" action="{{ url('upload-single-custom') }}" enctype="multipart/form-data">
                        @csrf
                        <div class="input-group">
                            <div class="custom-file">
                                <input type="file" name="file" class="custom-file-input" id="inputFileSingleCustom" required accept="image/*">
                                <label class="custom-file-label" for="inputFileSingleCustom">Choose file</label>
                            </div>
                            <div class="input-group-append">
                                <button type="submit" class="btn btn-primary float-right mr-2">Upload <i class="fa fa-upload"></i></button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div class="row mt-3">
                <div class="col-md-4">
                    <h6>Upload Multiple Custom</h6>
                </div>
                <div class="col-md-6">
                    <form method="POST" action="{{ url('upload-multiple-custom') }}" enctype="multipart/form-data">
                        @csrf
                        <div class="input-group">
                            <div class="custom-file">
                                <input type="file" name="files[]" class="custom-file-input" id="inputFileMultipleCustom" required accept="image/*" multiple>
                                <label class="custom-file-label" for="inputFileMultipleCustom">Choose file</label>
                            </div>
                            <div class="input-group-append">
                                <button type="submit" class="btn btn-primary float-right mr-2">Upload <i class="fa fa-upload"></i></button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>

6. Create routes

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UploadController; 

Route::get('/',                        [UploadController::class, 'index']);

Route::post('/upload-single',          [UploadController::class, 'uploadSingle']);
Route::post('/upload-multiple',        [UploadController::class, 'uploadMultiple']);

Route::post('/upload-single-custom',   [UploadController::class, 'uploadSingleCustom']);
Route::post('/upload-multiple-custom', [UploadController::class, 'uploadMultipleCustom']);

7. Finally open http://localhost/laravel-file-upload/public in the browser.

Access file from storage's uploads folder

asset('storage/folder_name/file_name')

Example:-

<img src="{{ asset('storage/uploads/pic1.png') }}">

Access file from public's uploads folder

asset('folder_name/file_name')

Example:-

<img src="{{ asset('uploads/pic2.png') }}">

Checkout my full laravel-file-upload example.

https://github.com/ultimateakash/laravel-file-upload

If you facing any issues. don't hesitate to comment below. I will be happy to help you.

Thanks.

Leave Your Comment