CodeBriefly
Tech Magazine

Handling File Upload in Laravel

0 1,604

Get real time updates directly on you device, subscribe now.

In this article, we will discuss “Handling File Upload in Laravel”. This is a common functionality for any of the programming languages, and frameworks as well. Today, I will show you how can you upload a file in your Laravel application. Here, we will create an example for uploading an image with validations. Also, if you are new in Laravel then you can start with our Laravel Collection to increase your knowledge.

Install New Laravel Application

You can use the following composer command to install the Laravel application.

composer create-project laravel/laravel laraImg --prefer-dist

Create Routes

Here, we will add two routes in “routes/web.php”.

Route::get('/upload-image', 'UploadController@getUploadForm');
Route::post('/upload-image', 'UploadController@postUploadForm');

“get” route is redirecting a user to upload form. And, “post” route is use to process the uploading.

Create Controller

Using the following Artisan command to create “UploadController”.

php artisan make:controller UploadController

After that, a newly created controller located at “app/Http/Controllers”.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UploadController extends Controller
{
    /**
     * Upload form
     */
    public function getUploadForm()
    {
        return view('upload-image');
    }

    /**
     * Post upload form
     */
    public function postUploadForm(Request $request)
    {
        $request->validate([
            'upload' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
        ]);

        // if you want to rename the image
        // $imageName = time().'.'.$request->upload->getClientOriginalExtension();

        // you can also use the original name
        $imageName = time().'-'.$request->upload->getClientOriginalName();
  
        // Upload file to public path in images directory
        $request->upload->move(public_path('images'), $imageName);
 
        return back()
            ->with('success','You have successfully upload image.')
            ->with('image',$imageName);

    }
}

Create Blade Template

Creating a blade template “upload-image.blade.php” in the “resources/views” directory, which contains the HTML form.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 7 - Image Upload Example</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <style>
        .wrap {
            padding: 30px 0;
        }
        h2 {
            margin-bottom: 30px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-sm-12">

                <div class="wrap">

                    <h2>Laravel Image Upload Example</h2>

                    @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>
                        <img src="images/{{ Session::get('image') }}" style="width:100%;">
                    @endif

                    @if (count($errors) > 0)
                        <div class="alert alert-danger">
                            <strong>Whoops!</strong> There were some problems with your file.
                            <ul>
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <form action="{{ URL::to('/upload-image') }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="row">
                            <div class="col-md-6">
                            <input type="file" name="upload">
                            </div>
                            <div class="col-md-6">
                                <button type="submit" class="btn btn-info">Upload</button>
                            </div>
                        </div>
                    </form>

                </div>

            </div>
        </div>    
    </div>
</body>
</html>

Testing

Use the Artisan serve command to run the Laravel application.

php artisan serve

This will start the Laravel Development Server, After that, you can use “http://127.0.0.1:8000/” in your browser to access your application.

Laravel Image Upload

Final Word’s

I hope you have enjoyed this tutorial, Today we’ve explored “Handling File Upload in Laravel”. We will discuss more on the file uploading such as multiple files upload, edit image and many more in our coming tutorials. Please feel free to add a comment if any queries.

Keep Learning, Stay Safe 🙂

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

Get real time updates directly on you device, subscribe now.

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More