Laravel 10 Image Crop and Upload Croppie JS Tutorial

Image cropping is a common requirement when dealing with user-uploaded images. Croppie.js provides an intuitive and user-friendly interface for cropping images on the client side before they are uploaded to the server.

If you want to incorporate image cropping functionality into your Laravel 10 web application using the lightweight JavaScript library Croppie.js, this tutorial is perfect for you.

In this step-by-step guide, you will learn how to use Croppie.js to crop images before uploading them using jquery AJAX in your Laravel 10 apps.

Laravel 10 Image Crop and Upload Croppie JS Tutorial

Steps to crop image before uploading using croppie js with ajax in Laravel 10 app:

  • Step 1 – Setup New Laravel 10 App
  • Step 2 – Setup Database with Laravel App
  • Step 3 – Create Crop Image File for Migration & Model
  • Step 4 – Define Routes
  • 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 – Setup New Laravel 10 App

First of all, start your terminal to download or install Laravel 10 new setup. Run the following commands in it to install the new Laravel 10 app on your system:

cd xampp\htdocs

Then

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

Step 2 – Setup Database with Laravel App

In this step, Navigate to downloaded Laravel 10 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 File for 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 – Define Routes

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

Route::get('image-crop', 'CropImageUploadController@index');

Route::post('save-crop-image', 'CropImageUploadController@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 8 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

Crop and save image using jquery in laravel, you have learned how to crop image before upload using jQuery with ajax in laravel.

Recommended Laravel Posts

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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