A Step-By-Step Guide To Laravel File Upload

Uploading files in Laravel is as easy as writing a few lines of code. All you need to do is create a file viewer where your user selects a file to upload, and a controller does the rest. There are many file upload options, but with our file uploader and the Filestack PHP SDK framework, you can perform the job efficiently.

First of all, it’s a robust, open-source PHP framework that simplifies and enhances web development. With its elegant toolkit, you can create full-featured web applications that upload files, images, and videos. This guide will show you how to make a file upload application if you are familiar with PHP.

To start, let’s take a look at three different types of Laravel file upload, look at some examples and discuss the simple steps involved. Moreover, you will learn how to upload files with the advanced version of the framework, which includes database validation and storage features. After that, we will explore the benefits of using the Filestack file uploader with the Filestack PHP SDK.

Let’s start! 

Key Takeaways

  • Advanced Features: Includes developing a sophisticated file upload system that integrates validation, database storage, and Bootstrap for user-friendly interfaces.
  • Filestack API: Delivers a robust solution for file uploads with secure cloud storage, built-in security features, and scalability.
  • Benefits: Focuses on enhancing security, scalability, and maintenance, freeing developers to concentrate on other development aspects.
  • Filestack’s Free Plan: Supports up to 100 monthly uploads with 1GB of storage and bandwidth.
  • Storage Flexibility with Laravel: Supports a range of storage drivers to customize file storage strategies suitable for various environments from local development to production.
  • Storage Configuration: Discusses how to configure and utilize different storage drivers to boost file upload and storage functionalities in Laravel applications.

How do you implement a simple Laravel file upload?

To create a view file with a file input for a simple laravel file uploader, you can use the code below. This will allow you to upload files using laravel.

Form::file('file_name');

In Form::open(), you need to add ‘files’ =>’ true’ as shown below. This will enable the form to be uploaded in multiple parts.

Form::open(array('url' => '/uploadfile','files'=>'true'));

Example

Step 1: Setting up the view file

To start, you need to create a view file that will handle the file upload. You can name this file uploadfile.php and place it in the resources/views directory. This is the code you should copy into the file:

<html>
   <body>
      <?php
         echo Form::open(array('url' => '/uploadfile','files'=>'true'));
         echo 'Select the file to upload.';
         echo Form::file('image');
         echo Form::submit('Upload File');
         echo Form::close();
      ?>
   </body>
</html>

Step 2: Generating the controller

Create a controller called UploadFileController by executing the following command.

php artisan make:controller UploadFileController --plain

Step 3: Receiving the output

After successfully executing the command, you will receive the output.

Step 4: Writing the controller logic

Next, copy the following lines of code in the app/Http/Controllers/UploadFileController.php file.
 app/Http/Controllers/UploadFileController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UploadFileController extends Controller {
   public function index() {
      return view('uploadfile');
   }
   public function showUploadFile(Request $request) {
      $file = $request->file('image');
   
      //Display File Name
      echo 'File Name: '.$file->getClientOriginalName();
      echo '<br>';
   
      //Display File Extension
      echo 'File Extension: '.$file->getClientOriginalExtension();
      echo '<br>';
   
      //Display File Real Path
      echo 'File Real Path: '.$file->getRealPath();
      echo '<br>';
   
      //Display File Size
      echo 'File Size: '.$file->getSize();
      echo '<br>';
   
      //Display File Mime Type
      echo 'File Mime Type: '.$file->getMimeType();
   
      //Move Uploaded File
      $destinationPath = 'uploads';
      $file->move($destinationPath,$file->getClientOriginalName());
   }
}

Step 5: Defining the routes

Add the following lines in app/Http/routes.php.

Route::get('/uploadfile','UploadFileController@index');
Route::post('/uploadfile','UploadFileController@showUploadFile');

Step 6: Testing the file upload

Test the upload file functionality.

How do I implement Laravel 8 File Upload with validation and store in database?

This Laravel file upload method generates two routes.  First, it creates a form with the get method. The second route is for the file upload or post file upload data.

To do this, develop a simple form using Bootstrap and its Form UI component. This allows you to choose a file, photo, or video for upload to your storage > public > uploads folder. You can also configure the database model and store the file path and name in the MySQL database.

How will you install the project?

First, open the command-line tool from the start menu and execute the following command to create a Laravel project from scratch.

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

Then, go into the freshly installed Laravel project directory.

cd laravel-file-upload

How do you connect to a database?

Next, to store files in Laravel, you need to set up a local web server with MAMP or XAMPP, create a database name in MySQL, and configure the .env file accordingly.

How do you create a file model and configure migration?

After that, to store the uploaded file information, open a migration file to define the table values in the database.

php artisan make:model File -m

 Then, go to database/migrations/timestamp_create_files_table file and define the table values

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFilesTable extends Migration
{
    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('file_path')->nullable();
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('files');
    }
}

 

After you are done there, add the $fillable property in the File model. Open the app/Models/File.php file and place the following code.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'file_path'
    ];
}

Finally, you are set to run the migration. You can also see the update in the MySQL database.

How do you create routes in Laravel?

Go to routes: web.php and create two routes. The first route handles the form creation, whereas the second route stores the file in the MySQL database.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUpload;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/upload-file', [FileUpload::class, 'createForm']);
Route::post('/upload-file', [FileUpload::class, 'fileUpload'])->name('fileUpload');

How do you create a file upload controller?

To make a file upload controller in Laravel, you need to define the business logic for uploading and storing files. Here are the steps to do that.

 

Execute this command to create the controller:

php artisan make:controller FileUpload

The app/Http/Controllers/FileUpload.php file contains two methods that handle the file upload. The first method, FileUpload controller, renders the view. The second method, fileUpload(), validates the file size, mime type, and other limitations.

Additionally, this method also stores the file in your storage/public/uploads folder and saves the file name and path in your database.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class FileUpload extends Controller
{
  public function createForm(){
    return view('file-upload');
  }
  public function fileUpload(Request $req){
        $req->validate([
        'file' => 'required|mimes:csv,txt,xlx,xls,pdf|max:2048'
        ]);
        $fileModel = new File;
        if($req->file()) {
            $fileName = time().'_'.$req->file->getClientOriginalName();
            $filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
            $fileModel->name = time().'_'.$req->file->getClientOriginalName();
            $fileModel->file_path = '/storage/' . $filePath;
            $fileModel->save();
            return back()
            ->with('success','File has been uploaded.')
            ->with('file', $fileName);
        }
   }
}

How do you create a Blade File in Laravel?

To create a blade file, start with creating a view and the file upload form.

Create a resources\views\file-upload.blade.php file, then place the following code inside it.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <title>Laravel File Upload</title>
    <style>
        .container {
            max-width: 500px;
        }
        dl, ol, ul {
            margin: 0;
            padding: 0;
            list-style: none;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <form action="{{route('fileUpload')}}" method="post" enctype="multipart/form-data">
          <h3 class="text-center mb-5">Upload File in Laravel</h3>
            @csrf
            @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <strong>{{ $message }}</strong>
            </div>
          @endif
          @if (count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                      <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
          @endif
            <div class="custom-file">
                <input type="file" name="file" class="custom-file-input" id="chooseFile">
                <label class="custom-file-label" for="chooseFile">Select file</label>
            </div>
            <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
                Upload Files
            </button>
        </form>
    </div>
</body>
</html>

This displays the file upload form, as well as a status message.

How can you start a Laravel application?

php artisan serve

That’s it!

 

How to implement a File upload with Filestack?

Now we will show you how to use Filestack to upload a file. Filestack is an advanced file upload API and service that securely stores files in the cloud.

Why use a third-party service like Filestack over building it yourself?

There are several reasons to use a service like Filestack over building your own service. First of all, It is risky to deal independently with scaling, security, and maintenance. Instead, you can use Filestack to scale quickly and painlessly in addition to minimizing risks. Moreover, Filestack has built-in protection and time-saving maintenance features. You don’t need to worry when you use Filestack. Because of this, you can focus on developing rather than maintaining, scaling, and securing your applications.

You can also try Filestack for free. The free plan as well as handles up to 100 monthly uploads with 1GB storage and 1GB bandwidth.

So let’s get started:

1. Are you registered with Filestack?

If you aren’t, then you need to sign up for a Filestack account on our registration page. After registering, log in and get your API Key.

2. Are you ready to start uploading?

Now let’s integrate the JavaScript file uploader widget from the Filestack library. The widget allows you to connect and upload from a variety of sources. For instance, if you want to upload from a URL or social media. Simply replace the contents of index.html with the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP File Upload</title>
</head>
<body>
    <style>
      .picker-content{
        height:300px;
        width:200px;
      }
    </style>
    <script src="//static.filestackapi.com/filestack-js/2.x.x/filestack.min.js"></script>
    <script type="text/javascript">
      document.addEventListener("DOMContentLoaded", function(event) { 
        const client = filestack.init(YOUR_API_KEY); 

        let options = {
          "displayMode": "inline",
          "container": ".picker-content",
          "accept": [
            "image/jpeg",
            "image/jpg",
            "image/png"
          ],
          "fromSources": [
            "local_file_system"
          ],
          "uploadInBackground": false,
          "onUploadDone": (res) => console.log(res),
        };

        picker = client.picker(options);
        picker.open();
      });
    </script>
    <div class="picker-content"></div>
</body>
</html>

One way to check if your upload widget is working properly is to try it yourself by uploading a file.  After the upload, you can log into your Filestack dashboard and see your newly uploaded file.

That’s it! You don’t even need the server to handle the file. Filestack is much better for scalability, security, and maintenance.

Why use the optional Filestack PHP Library?

The example above is the simplest example of a Filestack file upload. However, what if you want to access the file on your server and run some kind of post-processing? That is where you use the Filestack PHP library.

You can install the Filestack PHP library using composer. Alternatively, if you don’t have Composer installed then you can install it by going to the folder you created originally and following the documentation. (see link [1] for official documentation):

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

Once you are done, run php composer.phar.

After that, run require --prefer-dist filestack/filestack-php to install the Filestack SDK.

Now you have the Filestack library, let’s make a new PHP script to check your uploaded file.

Next, to do this, create a new file called. fileUploadFilestack.php and add the following (making sure to change the YOUR_API_KEY, YOUR_SECURITY_SECRET, and YOUR_FILE_HANDLE variables):

<?php
  require __DIR__ . '/vendor/autoload.php';
  use Filestack\FilestackClient;
  $client = new FilestackClient(YOUR_API_KEY);
  $security = new FilestackSecurity(YOUR_SECURITY_SECRET);

  $file_handle = YOUR_FILE_HANDLE;

  # get tags with client
  $result_json = $client->getTags($file_handle);

  # get tags with filelink
  $filelink = new Filelink($file_handle, YOUR_API_KEY, $security);

  $json_result = $filelink->getTags();

  # get safe for work flag with filelink
  $json_result = $filelink->getSafeForWork();
?>

This script runs a check on your file for work safety and stores the outcome in the$json_result variable.

That’s it!

For more information, you can visit: https://github.com/filestack/filestack-php.

Exploring Storage Drivers in Laravel

Laravel’s storage system provides an easy-to-use interface to interact with different storage drivers. These drivers allow you to store files in various locations such as local directories, cloud storage services, and FTP servers. Understanding how to leverage these drivers can enhance your application’s file handling capabilities.

Temporary Directory

When uploading files, it is often necessary to use a temporary directory to store files before they are processed or moved to their final destination. Laravel makes it easy to handle temporary storage using the storage_path helper, which points to the storage/app directory by default. You can use this temporary storage for tasks like virus scanning or file transformations before moving the files to a permanent storage location.

S3 Driver and S3 Bucket

Amazon S3 is a popular cloud storage solution that provides scalable storage in the cloud. Laravel’s S3 driver allows you to interact with S3 buckets seamlessly. By configuring the S3 driver in your config/filesystems.php file, you can upload files directly to an S3 bucket, ensuring high availability and scalability.

Configuring the S3 Driver

php

'disks' => [
    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
    ],
],

Custom Driver

In addition to the built-in drivers, Laravel allows you to create custom drivers to handle specific storage needs. A custom driver can be useful if you need to integrate with a proprietary storage solution or apply unique business logic before storing files.

Creating a Custom Driver

You can create a custom driver by extending Laravel’s storage system and registering your driver within a service provider. This allows you to define custom behaviors and configurations specific to your storage requirements.

FTP Driver

The FTP driver is another useful option for storing files on remote servers. This driver can be configured to connect to an FTP server and perform file operations such as uploading, downloading, and deleting files.

Configuring the FTP Driver

php

'disks' => [
    'ftp' => [
        'driver' => 'ftp',
        'host' => env('FTP_HOST'),
        'username' => env('FTP_USERNAME'),
        'password' => env('FTP_PASSWORD'),
        // Optional FTP settings...
    ],
],

Storage Driver

Overall, the term “storage driver” refers to any of the supported drivers (local, S3, FTP, custom) that Laravel can use to store files. Each driver offers different capabilities and can be configured to meet the specific needs of your application. By choosing the right storage driver, you can ensure that your application handles file storage efficiently and securely.

Learn how to integrate Filestack with various storage solutions.

Hope you have learned the basics of Laravel file upload.

Ready to get started building excellent Laravel File Upload applications using Filestack?

Sign up for free at Filestack to upload, transform and deliver content efficiently!

[1] https://getcomposer.org/download/

 

Read More →