Laravel 7/6 image upload example tutorial. Here we will show you how to upload image in laravel 7/6 with preview and validation.
And you will learn how you can upload image file in laravel 7/6 into the database and folder with server-side validation. This tutorial made easy to upload the image file to the folder and MySQL database in the laravel framework.
This example tutorial will guide you how to upload image in laravel 7/6 with validation and store image db and folder. As well as you will show a preview of the image file before uploading it into folder and database in laravel application.
Laravel 7/6 Image Upload and Validation
Just follow the steps and upload image in laravel storage folder and MySQL database 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, you need to download laravel fresh setup. Use the below command and download fresh new laravel setup :
composer create-project --prefer-dist laravel/laravel blog
2). Setup Database
After successfully install laravel Application, Go to your project .env file and set up database credential and move next step :
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 you need to create table name Image and it’s migration file. use the below command :
php artisan make:model Image -m
It command will create one model name Image and also create one migration file for Image table. After successfully run the command go to database/migrations file and put the below here :
<?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'); } }
Next migrate the table using the below command :
php artisan migrate
Recommended Post
Laravel Upload image Using Dropzone Example4). Create Image Upload Route
In this step, you need to create two routes in the web.php file. Go to /routes/web.php file and create two below routes here :
Route::get('image', 'ImageController@index'); Route::post('save', 'ImageController@save');
5). Create Image Upload Controller
Now, you need to create a controller name ImageController. Use the below command and create Controller :
php artisan make:controller ImageController
After successfully create controller go to app/controllers/ImageController.php and put the below code :
<?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
In this step, you need to create a blade view file. Go to app/resources/views and create one file name image.blade.php :
<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
<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
<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
Finally, you need to start development server. Use the php artisan serve command and start your server :
php artisan serve
If you want to run the project diffrent port so use this below command
php artisan serve --port=8080
Now you are ready to run our example so run bellow command to quick run.
http://localhost:8000/image
Conclusion
In this tutorial, you have successfully image upload in folder our laravel application. you uploaded the image in the database and folder with live preview our examples run quickly.
If you have any questions or thoughts to share, use the comment form below to reach us.
I have images folder on my Desktop. How do I save uploaded image there?