Showing posts with label laravel 6. Show all posts
Showing posts with label laravel 6. Show all posts

Sunday, 12 January 2020

Laravel 6 - Crop & Upload Image using jQuery with Ajax



Are you a learner of Laravel framework for web application development, So here in this post, you can find interesting topic like How to Crop an Image before uploading in Laravel framework. Here we have use Laravel 6 framework for make this type of feature in any web based application. If you want to learn How to Crop and Upload image in Laravel 6 framework by using jQuery with Ajax, so this post will help you to learn this topic.

Here we have use jQuery Croppie plugin used for Crop an Image before upload it. There are many jQuery plugin are available on internet for Crop image, but here we have use Croppie plugin with Laravel 6 framework for Crop image. Because it is widely used for Crop image, and it is easy to learn How to crop image. So, If you want to add feature like image crop for your web application, so you can use this plugin, because it is very easy to integrate in our web application.

In short, In this post we have use jQuery plugin for Crop an Image and by using Ajax we have upload on web server with Laravel 6 framework. Now in your mind how this Croppie plugin has work. So when page has been load into web browser, then this Croppie plugin has been initialize and once we have select image from our local computer then that selected image preview, we can see on web page. In that preview we can also zoom image, and we can drag the view port of the crop area also. So, this tutorial, you can find step by step process for How to Crop image by using Croppie plugin, and then after how to use Ajax for upload cropped image with Laravel 6 framework.

  • Download and Install Laravel 6 Framework
  • Create Controller Class
  • Create View Blade File
  • Set Route
  • Run Laravel 6 Application


Download and Install Laravel 6 Framework


If you want to use Laravel framework for you any web development task, so first you have to download and installed it in you local computer. For download Laravel 6 framework you have to go command prompt and go to directory in which you want to download Laravel framework, and after this you have to run following command in command prompt.


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


This command will make laravel6 folder and under this it will download Laravel 6 framework.




Create Controller Class


After download Laravel framework, so you are ready to use Laravel for web development. Here first we want to make Controller class for handle browser http request.So, for create Controller class we have to go command prompt and run following command

//Code
This command will make ImageCropController.php file in app/Http/Controllers folder. In this class we have make following method.

index() - This is the root method of this ImageCropController.php controller class. This method has load view file in browser.

upload() - This method has recieved Ajax request for upload Crop image. This method has received in image in binary string. By using base64_decode() method it will convert binary string to image format and by using file_put_contents() function image will be uploaded in crop_image folder. And lastly send response to Ajax request in Ajax format.

app/Http/Controllers/ImageCropController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageCropController extends Controller
{
    function index()
    {
     return view('image_crop');
    }

    function upload(Request $request)
    {
     if($request->ajax())
     {
      $image_data = $request->image;
      $image_array_1 = explode(";", $image_data);
      $image_array_2 = explode(",", $image_array_1[1]);
      $data = base64_decode($image_array_2[1]);
      $image_name = time() . '.png';
      $upload_path = public_path('crop_image/' . $image_name);
      file_put_contents($upload_path, $data);
      return response()->json(['path' => '/crop_image/' . $image_name]);
     }
    }
}



Create View Blade File


In Laravel framework, View Blade file has been used for display HTML output on web page. View file has been store under resources/views folder. Here we have make image_crop.blade.php file for this tutorial. In this file we have use Croppie plugin, Bootstrap library and jquery library.

resources/views/image_crop.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>How to Crop And Upload Image in Laravel 6 using jQuery Ajax</title>
  <script src="{{ asset('js/jquery.min.js') }}"></script>
  <link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}" />
    <link rel="stylesheet" href="{{ asset('css/croppie.min.css') }}" />
  <!--<script src="{{ asset('js/bootstrap.min.js') }}"></script>!-->
    <script src="{{ asset('js/croppie.min.js') }}"></script>
 </head>
 <body>
  <div class="container">    
    <br />
        <h3 align="center">How to Crop And Upload Image in Laravel 6 using jQuery Ajax</h3>
      <br />
      <div class="card">
        <div class="card-header">Crop and Upload Image</div>
        <div class="card-body">
          <div class="form-group">
            @csrf
            <div class="row">
              <div class="col-md-4" style="border-right:1px solid #ddd;">
                <div id="image-preview"></div>
              </div>
              <div class="col-md-4" style="padding:75px; border-right:1px solid #ddd;">
                <p><label>Select Image</label></p>
                <input type="file" name="upload_image" id="upload_image" />
                <br />
                <br />
                <button class="btn btn-success crop_image">Crop & Upload Image</button>
              </div>
              <div class="col-md-4" style="padding:75px;background-color: #333">
                <div id="uploaded_image" align="center"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <br />
          <br />
          
          <br />
          <br />
    </div>
 </body>
</html>

<script>  
$(document).ready(function(){
  
  $image_crop = $('#image-preview').croppie({
    enableExif:true,
    viewport:{
      width:200,
      height:200,
      type:'circle'
    },
    boundary:{
      width:300,
      height:300
    }
  });

  $('#upload_image').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]);
  });

  $('.crop_image').click(function(event){
    $image_crop.croppie('result', {
      type:'canvas',
      size:'viewport'
    }).then(function(response){
      var _token = $('input[name=_token]').val();
      $.ajax({
        url:'{{ route("image_crop.upload") }}',
        type:'post',
        data:{"image":response, _token:_token},
        dataType:"json",
        success:function(data)
        {
          var crop_image = '<img src="'+data.path+'" />';
          $('#uploaded_image').html(crop_image);
        }
      });
    });
  });
  
});  
</script>


Set Route


In Laravel framework, we have to set the route of Controller class method. For this we have to open routes/web.php. In this file we have to set the route of this Controller class method.

routes/web.php

Route::get('image_crop','ImageCropController@index');

Route::post('image_crop/upload', 'ImageCropController@upload')->name('image_crop.upload');


Run Laravel Application


For Run Laravel web application, we have to go command prompt and write following command.


php artisan serve


This command will start Laravel server and give you Laravel application base url. For check above code, you to enter http://127.0.0.1:8000/image_crop url, then after you can check above code. So, this is complete step by step process of image preview for crop image using jQuery Croppie plugin before uploading of image by using Ajax in Laravel 6 framework. If you want to get complete source code file, you can free email us at webslesson@gmail.com. We will send you source code file in zip folder.


Tuesday, 24 December 2019

Pagination in Laravel 6 with Next And Previous Button using Ajax



If you want to make Pagination in Laravel 6 on with Next and Previous Button Link, then this tutorial is for you. In this post, you can learn How to make Pagination only with Next and Previous Button Link in Laravel using Ajax. Here we will create customize next and previous pagination link in Laravel 6 framework using Ajax.

As Web Developer, we have know Pagination is a one type of design pattern, which has been widely used in most of web site of displaying content on web page. Pagination is a method of dividing large amount of content into different small piece and display large data into small pieces on web page, and suppose user want to view more data, then by using navigation option it can view next part of web content on web page.

There are different way we can use pagination in our web application. Some web developer has use divide content into different page number with navigation link for go to that page number content, some has use drop down list with option of page number, User has to select page number and he can go to data of that web page. And some one has use previous and next page link for go to next or previous page link. So, there is many different ways we can use pagination feature in our web application.

In this tutorial, we will make pagination with next and previous button link in Laravel 6 framework using Ajax. Laravel 6 framework has inbuilt pagination library for make pagination link. But here we want to add next and previous button link in pagination, For this here we can use simplePaginate() method in Laravel 6 framework. By using this eloquent simplePagiante() method we can add simple pagination with only previous and next button link.

But we want to provide more user experience in Laravel 6 pagination. So here we have use also use Ajax web technology. By using Ajax with Laravel 6 pagination, next and previous page data will be load without refresh of web page. So, if you are willing to add pagination with next and previous button link in Laravel 6 using Ajax, then you have to follow below step.




  1. Install Laravel 6 framework

  2. Make Database Connection

  3. Create Controller

  4. Create View Blade File

  5. Set Route

  6. Run Laravel Application


Install Laravel 6 framework


If want to developed application in Laravel, so first we want to download Laravel 6 framework and install in our local computer.

For this we have to go command prompt, and then after go to directoy in which we want to download and install this framwork and run following command.


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


Make Database Connection


Once Laravel framework has been install in define directory, first we want to make database connection. For this we have open .env file and in this file we have to define Mysql database configuration, which you can find below and it will make database connection.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


After making database connection, now we have to make one table with some data in Mysql database. For this you have to run following sql script. It will make table with some sample data in Mysql database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `sample_datas`
--

CREATE TABLE `sample_datas` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `first_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `last_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `sample_datas`
--

INSERT INTO `sample_datas` (`id`, `first_name`, `last_name`, `created_at`, `updated_at`) VALUES
(1, 'John', 'Smith', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(2, 'Peter', 'Parker', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(3, 'Larry', 'Degraw', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(5, 'Susan', 'Diener', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(6, 'William', 'Batiste', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(7, 'Butler', 'Tucker', '2019-10-14 00:30:00', '2019-10-19 03:24:32'),
(8, 'Eva', 'King', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(9, 'Dorothy', 'Hays', '2019-10-14 03:30:00', '2019-10-14 03:30:00'),
(10, 'Nannie', 'Ayers', '2019-10-14 03:30:00', '2019-10-14 03:30:00'),
(11, 'Gerald', 'Brown', '2019-10-14 04:30:00', '2019-10-14 04:30:00'),
(12, 'Judith', 'Smith', '2019-10-14 04:30:00', '2019-10-14 04:30:00'),
(14, 'Delores', 'Schumacher', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(15, 'Gloria', 'Romero', '2019-10-14 06:30:00', '2019-10-14 06:30:00'),
(17, 'Paul', 'Pate', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(18, 'Ryan', 'Hoang', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(19, 'Dixie', 'Smith', '2019-10-17 06:52:21', '2019-10-17 06:52:21'),
(20, 'Jack', 'Smith', '2019-10-17 23:22:30', '2019-10-19 00:39:56'),
(22, 'Ronald', 'Derby', '2019-10-18 00:00:01', '2019-10-18 00:00:01');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `sample_datas`
--
ALTER TABLE `sample_datas`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_datas`
--
ALTER TABLE `sample_datas`
  MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;




Create Controller


In Laravel framework, for handle http request we have to make controller class. For this we have to command prompt and run following command.


php artisan make:controller PaginationController


This command will make PaginationController.php file in app/Http/Controllers folder. In this class first we have to add use DB; statement, by using this statement we can use Laravel query builder class for database related operation. In this class we have make following method.
  • index() - This is the root method of this class. This method will fetch five data from Mysql table. And then after it will load that data in pagination_parent.blade.php view file.
  • fetch(Request $request) - This method will received Ajax request for fetch next five data from Mysql table. Here we have use simplePaginate() method for make pagination with Next and Previous button link. And lastly it will load data in pagination_child.blade.php file.

app/Http/Controllers/PaginationController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class PaginationController extends Controller
{
    function index()
    {
     $data = DB::table('sample_datas')->simplePaginate(5);
        return view('pagination_parent', compact('data'));
    }

    function fetch(Request $request)
    {
     if($request->ajax())
     {
      $data = DB::table('sample_datas')->simplePaginate(5);
         return view('pagination_child', compact('data'))->render();
     }
    }
}
?>


Create View Blade File


For display output in the form of HTML, In Laravel we have to create view blade file. In Laravel view file has been use blade templating engine for convert output in HTML format and view file has been store under resources/views folder.Here we have make following view file.

resources/views/pagination_parent.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 6 Pagination with Next Previous Button Link using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 6 Pagination with Previous Next Button Link using Ajax</h3>
     <br />
     @csrf
     <div class="table-responsive" id="table_data">
    @include('pagination_child')
   </div>
        </div>
 </body>
</html>


<script>
$(document).ready(function(){

 $(document).on('click', '.page-link', function(event){
    event.preventDefault(); 
    var page = $(this).attr('href').split('page=')[1];
    fetch_data(page);
 });

 function fetch_data(page)
 {
  var _token = $("input[name=_token]").val();
  $.ajax({
      url:"{{ route('pagination.fetch') }}",
      method:"POST",
      data:{_token:_token, page:page},
      success:function(data)
      {
       $('#table_data').html(data);
      }
    });
 }

});
</script>




resources/views/pagination_child.blade.php

<div class="table-responsive">
    <table class="table table-striped table-bordered">
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
        </tr>
        @foreach($data as $row)
        <tr>
            <td>{{ $row->first_name }}</td>
            <td>{{ $row->last_name }}</td>
        </tr>
        @endforeach
    </table>

    {!! $data->links() !!}
</div>


Set Route


In Laravel we have to set the route of controller method for display result on web page. For this we have to open routes/web.php file and in this file we have to define route.

routes/web.php

<?php

Route::get('/pagination', 'PaginationController@index');

Route::post('pagination/fetch', 'PaginationController@fetch')->name('pagination.fetch');

?>


Run Laravel Application


Once all code is ready, now we want to run Laravel application. For this first we have to go command prompt and run following command.


php artisan serve


This command will run Laravel server and provide use base url of laravel application. For test above code you have to run following url in your browser.


http://127.0.0.1:8000/pagination


So, this is step by step process for creating Pagination with Next and Previous button link in Laravel 6 using Ajax. So, We hope this tutorial will help you to learn this topic.