Cloudinary Blog

Laravel File Upload to a Local Server Or to the Cloud

Laravel File Upload to a Local Server Or to the Cloud

Currently, Laravel is the most renowned PHP framework, boasting of a large developer community; several open-source packages, such as Cashier, Sanctum, Scout, and Telescope; and a host of paid platforms, e.g., Laravel Forge, Envoyer, and Vapor. Laravel Forge & Envoyer ably supports deployment and use of Laravel production-based apps.


Introducing Cloudinary’s Laravel SDK. Learn the benefits and capabilities of the Laravel PHP framework and the way to upload to and transform files.


The sections below walk you through the process of setting up Laravel file uploads.

How to Optimize for Page Load Speed

Set Up a Laravel Project

  1. Install Composer and PHP on your development or production machine and then run this command:

    Copy to clipboard
    composer create-project --prefer-dist laravel/laravel upload
  2. Go to the upload directory and rename the env.example file to .env.

  3. Run the project with the command php artisan serve.

Your Laravel project is now up and running.

Set Up the Mechanics for File Uploads

  1. Create a file-upload controller (FileUpload Controller) in your project:

    Copy to clipboard
    php artisan make:controller FileUploadController
  2. Open the FileUploadController.php file and add a method for displaying the upload form:

    Copy to clipboard
    <?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    
    class FileUploadController extends Controller
    {
        public function showUploadForm()
        {
            return view('upload');
        }
    }
  3. Create an upload.blade.php file in the resources/views directory and populate the file with the code below:

    Copy to clipboard
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    
        <title>Laravel File Upload</title>
    
        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
    
        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }
    
            .full-height {
                height: 100vh;
            }
    
            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }
    
            .position-ref {
                position: relative;
            }
    
            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }
    
            .content {
                text-align: center;
            }
    
            .title {
                font-size: 84px;
            }
    
            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }
    
            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            <div class="content">
                <div class="title m-b-md">
                    Laravel File Upload
                </div>
    
                @if ($message = Session::get('success'))
                    <div class="alert alert-success alert-block">
                        <button type="button" class="close" data-dismiss="alert">×</button>
                            <strong>{{ $message }}</strong>
                    </div>
                @endif
    
                <div class="links">
                     <form action="/upload" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="row">
    
                            <div class="col-md-6">
                                <input type="file" name="file" class="form-control">
                            </div>
    
                            <div class="col-md-6">
                                <button type="submit" class="btn btn-success">Upload a File</button>
                            </div>
    
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </body>
    </html>

    The code above displays the form along with a confirmation message if the upload succeeded. Concurrently, the file-upload controller posts the form data to a /upload route in the routes/web.php file. Note: The related code will be shown later in this post.

  4. Go to the routes/web.php directory and add two routes: one to display the form and the other to process the file upload:

    Copy to clipboard
    Route::get('/upload', 'FileUploadController@showUploadForm');
    Route::post('/upload', 'FileUploadController@storeUploads');

Now reload the app and go to the /upload route. This page is displayed:

laravel file upload

Process the Uploads

Next, ensure that uploaded files are stored though the form by adding a storeUploads method to the FileUploadController.php file, as follows:

Copy to clipboard
….
public function storeUploads(Request $request)
    {
        $request->file('file')->store('images');

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

The code above grabs the file uploaded through the POST request, creates on your local service an images directory, and stores the file there.

Test it: upload a file for your app and see if the file is in the storage/app/images directory.

Note: For more details on a recently uploaded file, call these methods:

Copy to clipboard
 $fileName = $request->file('file')->getClientOriginalName();
 $extension = $request->file('file')->extension();
 $mime = $request->file('file')->getMimeType();
 $clientSize = $request->file('file')->getSize();

Set Up File Uploads to Cloudinary

Uploading files to the local disk and serving them yourself is rife with limitations, a major one being the lack of scalability. Best to outsource to an external service like Cloudinary, which, besides upload and storage capabilities, offers features for manipulating and managing media, including images, videos, audio, and other emerging types.

To enable file uploads to Cloudinary:

  1. Sign up for a free Cloudinary account, log in, and note your cloud name and API keys from the dashboard.

    media library

  2. Install Cloudinary’s Laravel SDK:

    Copy to clipboard
    composer require cloudinary-labs/cloudinary-laravel

    Note: Please follow the instructions in the #Installation section. Ensure you publish the config file and add your credentials to the .env file of your app.

  3. Rewrite the file-upload controller (FileUploadController.php) for straight uploads to the cloud:

    Copy to clipboard
    <?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    
    class FileUploadController extends Controller
    {
        public function showUploadForm()
        {
            return view('upload');
        }
    
        public function storeUploads(Request $request)
        {
            $response = cloudinary()->upload($request->file('file')->getRealPath())->getSecurePath();
    
            dd($response);
    
            return back()
                ->with('success', 'File uploaded successfully');
        }
    }

    The code above uploads the file straight to your Cloudinary account and returns the image URL by utilizing the cloudinary() helper function. We didn’t have to use the Cloudinary Facade.

Note: Be sure to replace <your-cloud-name>, <your-api-keys>, and <your-api-secret> with their values from your dashboard. Furthermore, for security while in production environments, always load those credentials from the environment variables. That is, invoke the config method to load the credentials before uploading the file to Cloudinary. dd($response) then dumps the response returned from Cloudinary for the uploaded file. Here’s an example of a response:

You can now store the returned URL in the database, and display the image to users anywhere in your app.

Leverage More Cloudinary Capabilities

Uploading files barely scratches the surface of media management. Cloudinary helps you administer the entire spectrum of your media’s lifecycle, end to end, from upload and transformation to optimization and delivery. Do check it out.

Want to Learn More About File Uploads?

Recent Blog Posts

Image-Editing Basics and a Tutorial for Automation With AI

You likely find yourself continually editing images for enhancement by eliminating flaws and tweaking the overall presentation, typically with software tools. Examples of basic editing are straightening, cleaning, and cropping images, as well as adjusting the contrast, exposure, and white balance. With advanced software like Cloudinary, you can automate not only editing tasks, such as quality adjustment and encoding, but also delivery.

Read more
Tips for Retaining Audience Through Engaging Videos

Measuring the level of interest your videos generate helps you produce compelling content. The measurement and optimization approach must, however, address the various aspects of each video, including the A/B test hypothesis and iterations. A high engagement rate spells effective videos; a low engagement rate calls for content improvement.

Read more
Forbes Cloud 100: When the Stars Align

In 2017, when Cloudinary first made the Forbes Cloud 100 as a ‘Rising Star,’ it was an incredibly proud moment for the company. In 2018 we graduated from Rising Star status to be acknowledged as part of the incredible Cloud 100, the top 100 SaaS companies in the world. Today marks our third consecutive year on this prestigious list.

Read more
A Cloudinary-Enhanced Student-ID App

I’m an instructional designer on Cloudinary’s Solutions and Training team. As the COVID-19 pandemic emerged in March, like other global organizations, we pivoted to set up virtual courses. As much as we looked forward to resuming in-person classes in the future, we switched gear to focus on the virtual way of learning.

Read more
Image Formats: Getting it Right

Image formats, which are standards for digital images, can be uncompressed, compressed, raster based, or vector based. You determine the DNA of your images with the formats you adopt, each of which offering different capabilities. For example, rasters generate images with pixels; vectors, with vectors or proportional formulas. PNGs can display logos without background; JPEGs always come with backgrounds. This article explains the main properties of the various image formats, including their basic concepts and pros and cons.

Read more