Laravel 7 Crop Image Before Upload in Controller

Laravel 7 Crop Image Before Upload in Controller

laravel crop image before upload in controller using jquery copper js. Here, we will show you how to simply crop image before upload into folder and database in laravel using copper js library of jQuery.

Whenever you are uploading images in Laravel. But you need to crop the image before uploading. Or you want to store the cropped image in the folder and database.

So, this tutorial will guide you on how to crop image before uploading into folder and database using cropper js and ajax in laravel.

As well, in this tutorial, when cropper js will be used to crop the image before uploading on the bootstrap model. So, crop the image will be in the bootstrap model. Then we will also use the bootstrap model in which the preview of the image will also be shown.

And will upload the cropped image to a server using ajax in laravel cropper js app.

Note that, In laravel, using Cropper.js is JavaScript plugin to use crop image before upload. So it also has many features like aspect ratio, move, zoom, rotate, full responsive, and mobile-friendly. You can use the image to move, zoom, rotate, etc.

This laravel crop image before upload using cropper js looks like:

laravel crop image before upload

You can visit by clicking this link to try live demo of Crop image Before Upload.

Laravel Crop Image Before Uploading using Cropper js Tutorial

Laravel crop image before upload tutorial, follow the following steps and learn how to use cropper js to crop image before uploading in laravel app:

  • Step 1: Install New Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Migration & Model
  • Step 4: Add Route
  • Step 5: Create Controller By Artisan
  • Step 6: Create Blade View
  • Step 7: Make Upload Directory
  • Step 8: Start Development Server

Step 1: Install New Laravel App

First of all, you need to download or install new laravel app to implement laravel crop image before upload using cropper js. So run the following command:

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

Step 2: Add Database Details

In this step, Go to your laravel crop image before upload with cropper js app. And open .env file. Then add the database details in .env file:

 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

Step 3: Migration & Model

In this step. you need to create a table name Picture and it’s migration file. So run the following command:

php artisan make:model Picture -m

This command will create one model name Picture and also create one migration file for the Pictures table.

Now, Navigate to database/migrations folder and open create_pictures_table.php file. And add the following code into it:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePicturesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('pictures', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('pictures');
    }
}

Now, open your terminal or cmd and run the following migrate command to create table into your database:

php artisan migrate

Step 4: Add Routes

In this step, you need to add routes in web.php file. So navigate to routes folder and open web.php file. And add the following routes into web.php file:

 Route::get('crop-image-upload', '[email protected]');
 Route::post('crop-image-upload ', '[email protected]');

Step 5: Create Controller By Artisan

Now, you need to create a controller name CropImageController.php. So you can run the following php artisan make:controller CropImageController command to create controller by an artisan command:

php artisan make:controller CropImageController

Then, Navigate to app/http/controllers folder and open CropImageController.php file. Then add the following code into your laravel CropImageController.php file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Picture;

class CropImageController extends Controller
{

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

    public function uploadCropImage(Request $request)
    {
        $folderPath = public_path('upload/');

        $image_parts = explode(";base64,", $request->image);
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];
        $image_base64 = base64_decode($image_parts[1]);

        $imageName = uniqid() . '.png';

        $imageFullPath = $folderPath.$imageName;

        file_put_contents($imageFullPath, $image_base64);

         $saveFile = new Picture;
         $saveFile->name = $imageName;
         $saveFile->save();
   
        return response()->json(['success'=>'Crop Image Uploaded Successfully']);
    }
}

Step 6: Create Blade view

In this step, you need to create a blade view file named crop-image-upload.blade.php file. So navigate to resources/views folder and create one file name crop-image-upload.blade.php. Then add the following code into the crop-image-upload.blade.php file:

<!DOCTYPE html>
<html>
<head>
<title>Laravel Cropper js - Crop Image Before Upload - Tutsmake.com</title>
<meta name="_token" content="{{ csrf_token() }}">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.js"></script>
</head>
<style type="text/css">
img {
display: block;
max-width: 100%;
}
.preview {
overflow: hidden;
width: 160px; 
height: 160px;
margin: 10px;
border: 1px solid red;
}
.modal-lg{
max-width: 1000px !important;
}
</style>
<body>
<div class="container">
<h1>Laravel Cropper Js - Crop Image Before Upload - Tutsmake.com</h1>
<input type="file" name="image" class="image">
</div>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Laravel Cropper Js - Crop Image Before Upload - Tutsmake.com</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="img-container">
<div class="row">
<div class="col-md-8">
<img id="image" src="https://avatars0.githubusercontent.com/u/3456749">
</div>
<div class="col-md-4">
<div class="preview"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="crop">Crop</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var $modal = $('#modal');
var image = document.getElementById('image');
var cropper;
$("body").on("change", ".image", function(e){
var files = e.target.files;
var done = function (url) {
image.src = url;
$modal.modal('show');
};
var reader;
var file;
var url;
if (files &amp;&amp; files.length > 0) {
file = files[0];
if (URL) {
done(URL.createObjectURL(file));
} else if (FileReader) {
reader = new FileReader();
reader.onload = function (e) {
done(reader.result);
};
reader.readAsDataURL(file);
}
}
});
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 3,
preview: '.preview'
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
$("#crop").click(function(){
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
canvas.toBlob(function(blob) {
url = URL.createObjectURL(blob);
var reader = new FileReader();
reader.readAsDataURL(blob); 
reader.onloadend = function() {
var base64data = reader.result; 
$.ajax({
type: "POST",
dataType: "json",
url: "crop-image-upload",
data: {'_token': $('meta[name="_token"]').attr('content'), 'image': base64data},
success: function(data){
console.log(data);
$modal.modal('hide');
alert("Crop image successfully uploaded");
}
});
}
});
})
</script>
</body>
</html> 

Note that, you need to include the below following javascript cropper js library into your crop-image-upload.blade.php file:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.js"></script>

Then, include the following script code into your crop-image-upload.blade.php file:

<script>
var $modal = $('#modal');
var image = document.getElementById('image');
var cropper;
$("body").on("change", ".image", function(e){
var files = e.target.files;
var done = function (url) {
image.src = url;
$modal.modal('show');
};
var reader;
var file;
var url;
if (files &amp;&amp; files.length > 0) {
file = files[0];
if (URL) {
done(URL.createObjectURL(file));
} else if (FileReader) {
reader = new FileReader();
reader.onload = function (e) {
done(reader.result);
};
reader.readAsDataURL(file);
}
}
});
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 3,
preview: '.preview'
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
$("#crop").click(function(){
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
canvas.toBlob(function(blob) {
url = URL.createObjectURL(blob);
var reader = new FileReader();
reader.readAsDataURL(blob); 
reader.onloadend = function() {
var base64data = reader.result; 
$.ajax({
type: "POST",
dataType: "json",
url: "crop-image-upload",
data: {'_token': $('meta[name="_token"]').attr('content'), 'image': base64data},
success: function(data){
$modal.modal('hide');
alert("Crop image successfully uploaded");
}
});
}
});
})
</script>

Here, the full source code of crop-image-upload.blade.php file with all javascript libraries, script code and css code:

<!DOCTYPE html>
<html>
<head>
<title>Laravel Cropper js - Crop Image Before Upload - Tutsmake.com</title>
<meta name="_token" content="{{ csrf_token() }}">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.js"></script>
</head>
<style type="text/css">
img {
display: block;
max-width: 100%;
}
.preview {
overflow: hidden;
width: 160px; 
height: 160px;
margin: 10px;
border: 1px solid red;
}
.modal-lg{
max-width: 1000px !important;
}
</style>
<body>
<div class="container mt-5">
<div class="card">
<h2 class="card-header">Laravel Cropper Js - Crop Image Before Upload - Tutsmake.com</h2>
<div class="card-body">
<h5 class="card-title">Please Selete Image For Cropping</h5>
<input type="file" name="image" class="image">
</div>
</div>  
</div>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Laravel Cropper Js - Crop Image Before Upload - Tutsmake.com</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="img-container">
<div class="row">
<div class="col-md-8">
<img id="image" src="https://avatars0.githubusercontent.com/u/3456749">
</div>
<div class="col-md-4">
<div class="preview"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="crop">Crop</button>
</div>
</div>
</div>
</div>
<script>
var $modal = $('#modal');
var image = document.getElementById('image');
var cropper;
$("body").on("change", ".image", function(e){
var files = e.target.files;
var done = function (url) {
image.src = url;
$modal.modal('show');
};
var reader;
var file;
var url;
if (files &amp;&amp; files.length > 0) {
file = files[0];
if (URL) {
done(URL.createObjectURL(file));
} else if (FileReader) {
reader = new FileReader();
reader.onload = function (e) {
done(reader.result);
};
reader.readAsDataURL(file);
}
}
});
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 3,
preview: '.preview'
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
$("#crop").click(function(){
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
canvas.toBlob(function(blob) {
url = URL.createObjectURL(blob);
var reader = new FileReader();
reader.readAsDataURL(blob); 
reader.onloadend = function() {
var base64data = reader.result; 
$.ajax({
type: "POST",
dataType: "json",
url: "crop-image-upload",
data: {'_token': $('meta[name="_token"]').attr('content'), 'image': base64data},
success: function(data){
console.log(data);
$modal.modal('hide');
alert("Crop image successfully uploaded");
}
});
}
});
})
</script>
</body>
</html> 

Step 7: Make Upload Directory

In this step, navigate to your laravel project root directory and open public directory. Inside public directory, create one new directory name upload.

Note that, if you have not created the upload directory in your laravel crop image before upload app, the error will be “Laravel show ErrorException file_put_contents failed to open stream: No such file or directory“.

To avoid this error, create upload directory inside public directory.

Step 8: Start Development Server

Finally, you need to start development server to run your laravel crop image before upload using cropper js app. So run 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/crop-image-upload 

Conclusion

laravel crop image before upload tutorial, you have learned how to crop image before upload into database and folder using cropper js. And successfully crop the image before uploading in folder.

Recommended Laravel Posts

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Livewire, Codeigniter, Vue JS, Angular JS, React Js, WordPress, and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *