Laravel 9 Crop & Resize Image Before Upload using jQuery Ajax

Laravel 9 crop and save image using croppie js; In this tutorial, we will learn how to crop images before uploading using jquery croppie js and ajax in laravel 9 apps.

Crop and Save Image using jQuery and Ajax in Laravel 9

Follow the following steps to crop image before upload croppie js in laravel 9 apps:

  • Step 1 – Install Laravel 9 App
  • Step 2 – Connecting App to Database
  • Step 3 – Create Crop Image Migration & Model
  • Step 4 – Add Routes For Crop Image Upload
  • Step 5 – Create Crop Image Controller Using Command
  • Step 6 – Create Crop Image Upload Blade View
  • Step 7 – Make Upload Folder
  • Step 8 – Run Development Server
  • Step 9 – Test This App

Step 1 – Install Laravel 9 App

First of all, open terminal and execute the following command to install or download laravel app for laravel 9 app for create crop image before upload using jQuery and ajax:

cd xampp\htdocs

Then

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

Step 2 – Connecting App to Database

In this step, Navigate to the downloaded laravel app root directory and open .env file. Then add your database details in .env file, as follow:

 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 – Create Crop Image Migration & Model

In this step, execute the following command on terminal to create one model and migration file for save crop image. So, open a command prompt and execute the following command:

php artisan make:model Image -m

After that, Navigate to database/migrations folder and open create_images_table.php. Then update the following code into create_images_table.php:

<?php

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

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

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

Now, open again cmd and run the following command to migrate the table into your select database:

php artisan migrate

Step 4 – Add Routes For Crop Image Upload

In this step, Navigate to the /routes folder and open web.php file. Then update the following routes into your web.php file:

use App\Http\Controllers\CropImageUploadController;

Route::get('image-crop', [CropImageUploadController::class, 'index']);
Route::post('save-crop-image', [CropImageUploadController::class, 'store']);

Step 5 – Create Crop Image Controller Using Command

In this step, open terminal and execute the following command to create ajax file upload controller file:

php artisan make:controller CropImageUploadController

Next, Navigate to app/http/controllers/ folder and open CropImageUploadController.php. Then add the following file uploading methods into your CropImageUploadController.php file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Image;

class CropImageUploadController extends Controller
{
    public function index()
    {
     return view('image-crop');
    }

    public function store(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 Image;
         $saveFile->title = $imageName;
         $saveFile->save();
   
        return response()->json(['success'=>'Crop Image Saved/Uploaded Successfully using jQuery and Ajax In Laravel']);
    }
}

Step 6 – Create Crop Image Upload Blade View

In this step, create one blade view file named image-crop.blade.php.

Now, navigate /resources/views and create one file name image-crop.blade.php. Then update the following code into your image-crop.blade.php file:

<html>  
<head>  
<title>Crop Image Using jQuery Croppie with Ajax in Laravel</title>  
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script
>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css" />
</head>  
<body>  
<div class="container mt-5">
<div class="card">
<div class="card-header">
Crop Image Using jQuery Croppie with Ajax in Laravel
</div>
<div class="card-body">
<input type="file" name="before_crop_image" id="before_crop_image" accept="image/*" />
</div>
</div>
</div>
</body>  
</html>
<div id="imageModel" class="modal fade bd-example-modal-lg" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Crop & Resize Upload Image in PHP with Ajax</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-8 text-center">
<div id="image_demo" style="width:350px; margin-top:30px"></div>
</div>
<div class="col-md-4" style="padding-top:30px;">
<br />
<br />
<br/>
<button class="btn btn-success crop_image">Save</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>  
$(document).ready(function(){
$image_crop = $('#image_demo').croppie({
enableExif: true,
viewport: {
width:200,
height:200,
type:'square' //circle
},
boundary:{
width:300,
height:300
}    
});
$('#before_crop_image').on('change', function(){
var reader = new FileReader();
reader.onload = function (event) {
$image_crop.croppie('bind', {
url: event.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
$('#imageModel').modal('show');
});
$('.crop_image').click(function(event){
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response){
$.ajax({
url:"{{url('save-crop-image')}}",  
type:'POST',
data: {'_token': $('meta[name="csrf-token"]').attr('content'), 'image': response},
success:function(data){
$('#imageModel').modal('hide');
alert('Crop image has been uploaded');
}
})
});
});
});  
</script>

Step 7 – Make Upload Folder

Now, open public directory and create one folder name upload.

Step 8 – Run Development Server

Now, Execute the following command to start the development server for your crop and resize image before upload laravel app:

 php artisan serve
If you want to run the project diffrent port so use this below command 
php artisan serve --port=8080  

Step 8 – Test This App

Now, open your browser and hit the following URLs into it:

http://localhost:8000/image-crop
OR hit in browser
http://localhost/blog/public/image-crop

If you want to remove public or public/index.php from URL In laravel, Click Me

Conclusion

Through this tutorial, we have learned how to crop images before uploading using jQuery with ajax in laravel 9 apps.

Recommended Laravel Tutorials

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, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL 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 *