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! 

What will you learn from the post?

To handle file uploads in Laravel, start by installing a Laravel project and creating and configuring routes. Then, create a Blade file, migrate databases, and implement validation on file upload components to ensure only specific file types (.csv, .txt, .xlx, .xls, .pdf) with a maximum size of 2MB are accepted, displaying status messages as needed. Finally, store the uploaded files in the database.

What will be the three ways of Laravel file upload you will learn in this guide?

Here are three distinct approaches to implementing a PHP uploader for your service. First, the Simple Laravel/PHP Way provides straightforward control over uploaded files. Second, Laravel 8 enables file upload with validation and storage in a database, offering a sensible and controlled method. Lastly, using Filestack’s PHP SDK is the easiest method, as it handles the complex backend infrastructure for you, simplifying file management.

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.


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'));


Step 1

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:

         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();

Step 2

Create a controller called UploadFileController by executing the following command.

php artisan make:controller UploadFileController --plain

Step 3

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

Step 4

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


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';

Step 5

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


Step 6

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

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) {
    public function down()


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.

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

class File extends Model
    use HasFactory;
    protected $fillable = [

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.

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.

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){
        '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;
            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">
    <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>
        .container {
            max-width: 500px;
        dl, ol, ul {
            margin: 0;
            padding: 0;
            list-style: none;
    <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>
            @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <strong>{{ $message }}</strong>
          @if (count($errors) > 0)
            <div class="alert alert-danger">
                    @foreach ($errors->all() as $error)
                      <li>{{ $error }}</li>
            <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>
            <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
                Upload Files

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">
    <meta charset="UTF-8">
    <title>PHP File Upload</title>
    <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": [
          "fromSources": [
          "uploadInBackground": false,
          "onUploadDone": (res) => console.log(res),

        picker = client.picker(options);
    <div class="picker-content"></div>

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):

  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.

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 →