In this tutorial you will learn about the Laravel 7/6 Image Upload with Validation and its application with practical example.
In this Laravel 7/6 Image Upload with validation example, we will learn how to upload and save image in laravel 7/6. In this laravel simple image upload example, I’ll show you how to validate upload image into folder and then save it into database. In this tutorial before saving image into database we will validate image and then save it into directory using. Before uploading the image we will perform server side validation. After successfully image upload into the database and folder we will display success message on the screen.
Laravel 7/6 Image Upload with Validation
- Install Laravel Fresh App
- Setup Database Details
- Generate Image Migration & Model
- Create Image Upload Route
- Create Image Controller
- Create Image Upload and Preview Blade View
- Start Development Server
1). Install Laravel Fresh App
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
2). Setup Database
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here |
3). Generate Image Migration & Model
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan make:model Image -m |
The above command will create a model name Image and also create a migration file for Image table. Now, go to database/migrations file and put the below here :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateImagesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('images', function (Blueprint $table) { $table->increments('id'); $table->string('image'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('images'); } } |
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan migrate |
4). Create Image Upload Route
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 |
Route::get('image', 'ImageController@index'); Route::post('save', 'ImageController@save'); |
5). Create Image Upload Controller
Now, lets create a controller named ImageController using command given below –
1 |
php artisan make:controller ImageController |
Now, go to app/controllers/ImageController.php and put the below code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator,Redirect,Response,File; Use App\Image; class ImageController extends Controller { public function index() { return view('image'); } public function save() { request()->validate([ 'fileUpload' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); if ($files = $request->file('fileUpload')) { $destinationPath = 'public/image/'; // upload path $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension(); $files->move($destinationPath, $profileImage); $insert['image'] = "$profileImage"; } $check = Image::insertGetId($insert); return Redirect::to("image") ->withSuccess('Great! Image has been successfully uploaded.'); } } |
6). Create Image Upload and Preview Blade view
Now we will create a blade view file. Go to app/resources/views and create one file name image.blade.php :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<html lang="en" class=""> <head> <meta charset="UTF-8"> <title>Laravel Image Upload Tutorial Example From Scratch</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" /> </head> <body> <div class="container"> <br><br><br> @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> <br> @endif <h2>File Upload & Image Preview</h2> <p class="lead">No Plugins <b>Just Javascript</b></p> <!-- Upload --> <form id="file-upload-form" class="uploader" action="{{url('save')}}" method="post" accept-charset="utf-8" enctype="multipart/form-data"> @csrf <input id="file-upload" type="file" name="fileUpload" accept="image/*" onchange="readURL(this);"> <label for="file-upload" id="file-drag"> <img id="file-image" src="#" alt="Preview" class="hidden"> <div id="start" > <i class="fa fa-download" aria-hidden="true"></i> <div>Select a file or drag here</div> <div id="notimage" class="hidden">Please select an image</div> <span id="file-upload-btn" class="btn btn-primary">Select a file</span> <br> <span class="text-danger">{{ $errors->first('fileUpload') }}</span> </div> <button type="submit" class="btn btn-success">Submit</button> </label> </form> </body> </html> |
Put css on image.blade.php in head section
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
<style class=""> @import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css); @import url("https://fonts.googleapis.com/css?family=Roboto"); html, body, * { box-sizing: border-box; font-size: 16px; } html, body { height: 100%; text-align: center; } body { padding: 2rem; background: #f8f8f8; } h2 { font-family: "Roboto", sans-serif; font-size: 26px; line-height: 1; color: #454cad; margin-bottom: 0; } p { font-family: "Roboto", sans-serif; font-size: 18px; color: #5f6982; } .uploader { display: block; clear: both; margin: 0 auto; width: 100%; max-width: 600px; } .uploader label { float: left; clear: both; width: 100%; padding: 2rem 1.5rem; text-align: center; background: #fff; border-radius: 7px; border: 3px solid #eee; transition: all .2s ease; user-select: none; } .uploader label:hover { border-color: #454cad; } .uploader label.hover { border: 3px solid #454cad; box-shadow: inset 0 0 0 6px #eee; } .uploader label.hover #start i.fa { transform: scale(0.8); opacity: 0.3; } .uploader #start { float: left; clear: both; width: 100%; } .uploader #start.hidden { display: none; } .uploader #start i.fa { font-size: 50px; margin-bottom: 1rem; transition: all .2s ease-in-out; } .uploader #response { float: left; clear: both; width: 100%; } .uploader #response.hidden { display: none; } .uploader #response #messages { margin-bottom: .5rem; } .uploader #file-image { display: inline; margin: 0 auto .5rem auto; width: auto; height: auto; max-width: 180px; } .uploader #file-image.hidden { display: none; } .uploader #notimage { display: block; float: left; clear: both; width: 100%; } .uploader #notimage.hidden { display: none; } .uploader progress, .uploader .progress { display: inline; clear: both; margin: 0 auto; width: 100%; max-width: 180px; height: 8px; border: 0; border-radius: 4px; background-color: #eee; overflow: hidden; } .uploader .progress[value]::-webkit-progress-bar { border-radius: 4px; background-color: #eee; } .uploader .progress[value]::-webkit-progress-value { background: linear-gradient(to right, #393f90 0%, #454cad 50%); border-radius: 4px; } .uploader .progress[value]::-moz-progress-bar { background: linear-gradient(to right, #393f90 0%, #454cad 50%); border-radius: 4px; } .uploader input[type="file"] { display: none; } .uploader div { margin: 0 0 .5rem 0; color: #5f6982; } .uploader .btn { display: inline-block; margin: .5rem .5rem 1rem .5rem; clear: both; font-family: inherit; font-weight: 700; font-size: 14px; text-decoration: none; text-transform: initial; border: none; border-radius: .2rem; outline: none; padding: 0 1rem; height: 36px; line-height: 36px; color: #fff; transition: all 0.2s ease-in-out; box-sizing: border-box; background: #454cad; border-color: #454cad; cursor: pointer; } .text-danger{ color: red; } </style> |
Put the script on image.blade.php after closing of body tag
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> </div> <script> function readURL(input, id) { id = id || '#file-image'; if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $(id).attr('src', e.target.result); }; reader.readAsDataURL(input.files[0]); $('#file-image').removeClass('hidden'); $('#start').hide(); } } </script> |
7). Start Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://localhost:8000/image |