How to Upload File in Laravel Framework?

Last updated on March 15, 2023

To upload a file in the Laravel framework, you will need to create a route, blade file, and controller. In this article, we will create a file uploader step by step in the fresh Laravel application.

Table of Contents

  1. Install Laravel Application
  2. Create Controller and Methods
  3. Create Blade File
  4. Create Routes

1. Install Laravel Application

To begin with, install a fresh Laravel application. So open the terminal and run the below command in the root directory of the local web server for installation.

composer create-project laravel/laravel your-project-name

OR if you have installed the Laravel installer then simple run below,

laravel new your-project-name

2. Create Controller and Methods

Create controller with below command,

php artisan make:controller FileUploadController

This command will be creating FileUploadController.php without any method inside the app/Http/Controllers directory.

Once the controller is created, we need to add an index() method to load the blade file from the views.

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

It is a simple method that takes the view file from the resources/views directory. As you can see we passed the 'file-upload' string into the view() function which is the blade file name, we will be creating inside the resources/views directory in the next step.

Another method we need in the same controller is upload(), which performs below tasks,

  • File validation
  • Upload file
  • If uploaded then redirects back to the previous method with a success message.
public function upload(Request $request)
{
    // it validates the file
    $validated = $request->validate([
        'image' => 'required|image|mimes:jpg,png,jpeg,gif',
    ]);

    // it uploads the file
    $path = $request->file('image')->store('uploads');

    // redirect back with success message
    return redirect()->back()->with('message', 'Image has been successfully uploaded.');
}

The upload() method has three features, the first validates the file and its extension. It checks if the file is an image and if its extension is allowed. In the validation, jpg, png, jpeg, and gif extensions are allowed.

The second script runs when the file passes the validation rules, and it uploads the file into the storage/app/uploads directory.

The third script redirects back to the previous method with success messages.

We created two methods inside the controller which are required for uploading the file. Below is full code of FileUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileUploadController extends Controller
{
    public function index()
    {
        return view('file-upload');
    }

    public function upload(Request $request)
    {
        // it validates the file
        $validated = $request->validate([
            'image' => 'required|image|mimes:jpg,png,jpeg,gif',
        ]);

        // it uploads the file
        $path = $request->file('image')->store('uploads');

        // redirect back with success message
        return redirect()->back()->with('message', 'Image has been successfully uploaded.');
    }
}

3. Create Blade File

Create a blade file with name file-upload.blade.php inside resources/views directory and copy paste below code.

<!DOCTYPE html>
<html>
<body>

    @if ($errors->any())
        <div>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    @if(session()->has('message'))
        <div>
            {{ session()->get('message') }}
        </div>
    @endif

    <form method="POST" enctype="multipart/form-data" action="{{ route('upload') }}">
        @csrf
        <label>File: </label>
        <input type="file" name="image">
        <input type="submit" name="submit">
    </form>

</body>
</html>

The blade file contains an HTML form and two if-statements. The HTML form contains one input field and button that posts data to the upload route, as you can see it is mentioned in the action attribute. The form also has a CSRF (Cross-Site Request Forgery) field that is required in Laravel.

4. Create Routes

We need two routes, one for index() method and second for upload() method. So open web.php from routes directory and add below routes.

use App\Http\Controllers\FileUploadController;

Route::get('/file-upload', [FileUploadController::class, 'index']);
Route::post('/upload', [FileUploadController::class, 'upload'])->name('upload');

In these routes, the first route creates /file-upload slug and maps with the index() method from FileUploadController. Similarly, the second route creates /upload slug and maps with the upload() method from FileUploadController.

Next, we need to test if Laravel runs the form, validates the files, and uploads the image. So in the terminal run the below command,

php artisan serve

It will return following URL,

http://127.0.0.1:8000/

Open following URL that shows image upload form.

http://127.0.0.1:8000/file-upload

Click on file upload and select any image from your computer and submit it for uploading.

Conclusion

This article explains the steps for validating and uploading files through the form in the Laravel framework. It covered the following steps,

  • Installation of Fresh Laravel application
  • Controllers and Methods for handling file upload
  • Blade file for HTML form
  • Routes for HTML form and file upload


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: Laravel,