Topic: Programming

Laravel 6 Ajax CRUD Example 0

Laravel 6 Ajax CRUD Example

Today, We want to share with you Laravel 6 Ajax CRUD.In this post we will show you , hear for Laravel 6 – Create First Ajax CRUD Application from Scratch we will give you demo and example for implement.In this post, we will learn about AJAX CRUD Tutorial Using jQuery, JSON and Laravel 6 with an example.

Laravel 6 Ajax CRUD Example

There are the Following The simple About Laravel6 Ajax CRUD Full Information With Example and source code.

As I will cover this Post with live Working example to develop Ajax CRUD [CReate Update Delete] with PHP Laravel6, so the some major files and Directory structures for this example is following below.

Phase 1: Install Laravel 6

install fresh Laravel 6 version application

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

Phase 2: Install Yajra Datatable

composer require yajra/laravel-datatables-oracle

config/app.php
.....

'providers' => [
	....
	Yajra\DataTables\DataTablesServiceProvider::class,
]

'aliases' => [
	....
	'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]

.....

Phase 3: Database Configuration

crud application of laravel 6

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=socialapp
DB_USERNAME=root
DB_PASSWORD=root

Phase 4: Create Migration Table

Laravel 6 php artisan command,

php artisan make:migration create_suggetions_table --create=suggetions

<?php
 
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class CreateSuggetionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('suggetions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('suggetions');
    }
}

php artisan migrate

Phase 5: Create Route

routes/web.php

Route::resource('ajaxsuggetions','SuggetionsAjaxController');

Phase 6: Add Controller and Model

app/Http/Controllers/SuggetionsAjaxController.php

<?php
         
namespace App\Http\Controllers;
          
use App\Suggetions;
use Illuminate\Http\Request;
use DataTables;
        
class SuggetionsAjaxController extends Controller
{

    public function index(Request $request)
    {
   
        if ($request->ajax()) {
            $data = Suggetions::latest()->get();
            return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){
   
                           $btn = '<a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editSuggetions">Edit</a>';
   
                           $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteSuggetions">Delete</a>';
    
                            return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
      
        return view('suggetionAjax',compact('suggetions'));
    }
     
    public function store(Request $request)
    {
        Suggetions::updateOrCreate(['id' => $request->suggetion_id],
                ['name' => $request->name, 'detail' => $request->detail]);        
   
        return response()->json(['success'=>'Suggetions saved successfully.']);
    }

    public function edit($id)
    {
        $suggetion = Suggetions::find($id);
        return response()->json($suggetion);
    }
  
    public function destroy($id)
    {
        Suggetions::find($id)->delete();
     
        return response()->json(['success'=>'Suggetions deleted successfully.']);
    }
}

app/Suggetions.php

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Suggetions extends Model
{
    protected $fillable = [
       'name', 'detail'
    ];
}

Phase 7: Add Blade Files

resources/views/suggetionAjax.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel6 Ajax CRUD tutorial using Datatable - pakainfo.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
    
<div class="container">
    <h1>Simple Laravel 6 Ajax CRUD tutorial using Datatable - pakainfo.com</h1>
    <a class="btn btn-success" href="javascript:void(0)" id="createNewSuggetions"> Create New Suggetions</a>
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Details</th>
                <th width="280px">Action</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
   
<div class="modal fade" id="ajaxModel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modelHeading"></h4>
            </div>
            <div class="modal-body">
                <form id="suggetionForm" name="suggetionForm" class="form-horizontal">
                   <input type="hidden" name="suggetion_id" id="suggetion_id">
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Name</label>
                        <div class="col-sm-12">
                            <input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
                        </div>
                    </div>
     
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Details</label>
                        <div class="col-sm-12">
                            <textarea id="detail" name="detail" required="" placeholder="Enter Details" class="form-control"></textarea>
                        </div>
                    </div>
      
                    <div class="col-sm-offset-2 col-sm-10">
                     <button type="submit" class="btn btn-primary" id="saveBtn" value="create">Save changes
                     </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
    
</body>
    
<script type="text/javascript">
  $(function () {
     
      $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
    });
    
    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('ajaxsuggetions.index') }}",
        columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex'},
            {data: 'name', name: 'name'},
            {data: 'detail', name: 'detail'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });
     
    $('#createNewSuggetions').click(function () {
        $('#saveBtn').val("create-suggetion");
        $('#suggetion_id').val('');
        $('#suggetionForm').trigger("reset");
        $('#modelHeading').html("Create New Suggetions");
        $('#ajaxModel').modal('show');
    });
    
    $('body').on('click', '.editSuggetions', function () {
      var suggetion_id = $(this).data('id');
      $.get("{{ route('ajaxsuggetions.index') }}" +'/' + suggetion_id +'/edit', function (data) {
          $('#modelHeading').html("Edit Suggetions");
          $('#saveBtn').val("edit-user");
          $('#ajaxModel').modal('show');
          $('#suggetion_id').val(data.id);
          $('#name').val(data.name);
          $('#detail').val(data.detail);
      })
   });
    
    $('#saveBtn').click(function (e) {
        e.preventDefault();
        $(this).html('Sending..');
    
        $.ajax({
          data: $('#suggetionForm').serialize(),
          url: "{{ route('ajaxsuggetions.store') }}",
          type: "POST",
          dataType: 'json',
          success: function (data) {
     
              $('#suggetionForm').trigger("reset");
              $('#ajaxModel').modal('hide');
              table.draw();
         
          },
          error: function (data) {
              console.log('Error:', data);
              $('#saveBtn').html('Save Changes');
          }
      });
    });
    
    $('body').on('click', '.deleteSuggetions', function () {
     
        var suggetion_id = $(this).data("id");
        confirm("Are You sure want to delete !");
      
        $.ajax({
            type: "DELETE",
            url: "{{ route('ajaxsuggetions.store') }}"+'/'+suggetion_id,
            success: function (data) {
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });
     
  });
</script>
</html>

Download Laravel 6 Crud Source Code

Now We can test it by using simple following command:

php artisan serve

Now We can open bellow URL on your browser:

http://localhost:8000/ajaxsuggetions

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Laravel 6 Ajax CRUD Example Step By Step.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

PHP cURL Multiple Asynchronous Http Requests 0

PHP cURL Multiple Asynchronous Http Requests

Today, We want to share with you PHP cURL Multiple Asynchronous Http Requests.In this post we will show you wordpress plugin require another plugin, hear for PHP Curl Examples – PHP cURL Post, Get, Header we will give you demo and example for implement.In this post, we will learn about Building a REST client with asynchronous calls using PHP and curl with an example.

PHP cURL Multiple Asynchronous Http Requests

There are the Following The simple About PHP cURL Multiple Asynchronous Http Requests Full Information With Example and source code.

As I will cover this Post with live Working example to develop php curl without waiting for response, so the synchronous and asynchronous request in php is used for this example is following below.

PHP: Setting cURL timeout options.

<?php

$url = 'http://localhost/tester/log.php';

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($ch);
$data =  json_decode($response,true);

if(curl_errno($ch)){
    throw new Exception(curl_error($ch));
} else {
	print_r($data);
}

PHP: Set custom headers with cURL

$url = 'http://localhost/test/file.php';
$ch = curl_init($url);

$customHeaders = array(
    'Accept-Encoding: gzip, deflate, br',
    'Cookie: PHPSESSID=BBRP012565Iidjkd8965;',
    'Referer: https://www.google.com/'
);

curl_setopt($ch, CURLOPT_HTTPHEADER, $customHeaders);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($ch);
$data =  json_decode($response,true);

if(curl_errno($ch)){
    throw new Exception(curl_error($ch));
} else {
	print_r($data);
}

Using sleep to add delay or increase execution time

<?php
echo date('H:i:s');
sleep(15);
flush();
echo "<br>";
echo date('H:i:s');
?>

sleep(30);

php curl_exec stopped

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); 
curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
curl_setopt($ch, CURLOPT_URL, "https://myurl"); 
curl_setopt($ch, CURLOPT_POSTFIELDS, "post_field1=value1"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_FAILONERROR, false); 
$server_output = curl_exec ($ch); // <------ IT DIES HERE INSIDE 
 curl_close ($ch); 
return $server_output; 

Multiple asynchronous http calls using curl

Single curl request

<?php

$t1 = microtime(true);

function fetchContent($Url) {
	if (!function_exists('curl_init')){
	die('Sorry cURL is not installed!');
	}
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $Url);
	curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");
	curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	$output = curl_exec($ch);
	curl_close($ch);
	return $output;
}

echo "<pre style='width:100%;height:40%'>";
echo fetchContent('https://your-domain-name.com/api/admin/php/products/fetched-product/fetch1.php');
echo "</pre>";

echo '<hr>';

echo "<pre style='width:100%;height:40%'>";
echo fetchContent('https://your-domain-name.com/api/admin/php/products/fetched-product/fetch2.php');
echo "</pre>";

echo 'fetched for: ' . (microtime(true) - $t1) . "\n";

multiple http requests using curl

<?php

if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}

$ch = array();
$mh = curl_multi_init();
$total = 100;

$t1 = microtime(true);

$URLs = array( "https://your-domain-name.com/api/admin/php/products/fetched-product/fetch2.php",
"https://your-domain-name.com/api/admin/php/products/fetched-product/fetch2.php");

$i = 0;
foreach($URLs as $url) {
$ch[$i] = curl_init();
curl_setopt($ch[$i], CURLOPT_URL, $url);
curl_setopt($ch[$i], CURLOPT_HEADER, 0);
curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, true);

curl_multi_add_handle($mh, $ch[$i]);
$i ++;
}

$active = null;
do {
$mrc = curl_multi_exec($mh, $active);
//usleep(100); 
} while ($active);

$content = array();

$i = 0;
foreach ($ch AS $i => $c) {
$content[$i] = curl_multi_getcontent($c);
curl_multi_remove_handle($mh, $c);
}

curl_multi_close($mh);

echo "<pre style='width:100%;height:40%'>";
echo $content[0];
echo "</pre>";

echo '<hr>';

echo "<pre style='width:100%;height:40%'>";
echo $content[1];
echo "</pre>";

echo 'fetched for: ' . (microtime(true) - $t1) . "\n";

PHP Sleep Functions

while (true) {
    $getProducts = CurlPage($YOUR_URL);
    $getPage1httpCode = $getProducts['httpCode'];
    if ($getPage1httpCode === 200) {
        $DATA = $getProducts['Data'];
        break;
    }
    sleep(rand(5, 10));
    $tracks++;
    if ($tracks === 5) {
        die('Sorry, Fatal Error');
    }
}

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about PHP cURL Multiple Asynchronous Http Requests.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

WooCommerce Webhooks verification in PHP 0

Handling Incoming WooCommerce Webhooks verification in PHP

Today, We want to share with you Handling Incoming WooCommerce Webhooks verification in PHP.In this post we will show you wordpress plugin require another plugin, hear for WebHook verification doesn’t match – PHP, we will give you demo and example for implement.In this post, we will learn about Proper way to verify the signature coming from WooCommerce webhooks, with an example.

Handling Incoming WooCommerce Webhooks verification in PHP

There are the Following The simple About Handling Incoming wordpress Woo-Commerce Webhooks verification in PHP Full Information With Example and source code.

As I will cover this Post with live Working example to develop validating webhook using HMAC in PHP, so the Woocommerce Webhooks Secret Key is used for this example is following below.

WebHook verification in PHP

$sig = base64_encode(hash_hmac('sha256', $request_body, $secret, true));

  • $secret => Your secret,
  • $request_body => The request body{{ which can be fetched with file_get_contents(‘php://input’) }};
  • $sig => X-Wc-Webhook-Signature request header.

how to create a webhook url wordpress?

<?php

header('Content-Type: application/json');
$request = file_get_contents('php://input');
$req_dump = print_r( $request, true );
$json_data = file_put_contents( 'request.log', $req_dump );
$action = json_decode($json_data, true);
?>

Receiving webhook data and save them in db

$json_data = file_get_contents('php://input');
$action = json_decode($json_data, true);

Webhook handling with PHP

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $raw_data = file_get_contents('php://input');
    $payload = json_decode($raw_data, true);

    if (is_array($payload)) {
        $fh = fopen("log_data.txt", "a+");

        if ($fh) {
            fwrite($fh, date('Y-m-d H:i:s', time()).PHP_EOL);
            fclose($fh);
        } else {
            wh_error("Sorry, Unable to open file!");
        }
    } else {
        wh_error("sorry, Invalid payload!");
    }
} else {
    wh_error("sorry, Invalid request!");
}

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Handling Incoming WooCommerce Webhooks verification in PHPLaravel.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Laravel 6 Check if a File exists before create directory 0

Laravel 6 Check if a File exists before create directory

Today, We want to share with you Laravel 6 Check if a File exists before create directory.In this post we will show you wordpress plugin require another plugin, hear for laravel storage create directory if not exists we will give you demo and example for implement.In this post, we will learn about Determining If a File Exists in Laravel 6 with an example.

Laravel 6 Check if a File exists before create directory

There are the Following The simple About Laravel-6 Check if a File exists before make directory Full Information With Example and source code.

As I will cover this Post with live Working example to develop How to check if file exists or not in Laravel 6?, so the Check if a File exists in Laravel 6 is used for this example is following below.

Example 1: Using File System:

Laravel Simple isCheckFile methods in File System

public function isCheckFile(Request $request)
{
    $orignal_path = public_path('upload/tamilrokers.png');
    $finalResults = File::exists($orignal_path);
    dd($finalResults);
}

Example 2: Using Storage System:

Laravel Simple isCheckFile methods in torage System

public function isCheckFile()
{
    $finalResults = Storage::exists('upload/tamilrokers.png');
    dd($finalResults);
}

Example 3: Using Core PHP:

Core PHP Simple isCheckFile methods

public function isCheckFile()
{
    $orignal_path = public_path('upload/tamilrokers.png');
    $finalResults = file_exists($orignal_path);
    dd($finalResults);
}

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Laravel6 Check if a File exists before create directory.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Laravel 6 List All Files in Directory Examples 0

Laravel 6 List All Files in Directory

Today, We want to share with you Laravel 6 List All Files in Directory.In this post we will show you wordpress plugin require another plugin, hear for all files in one directory Laravel 6 we will give you demo and example for implement.In this post, we will learn about How to get file name, file size and sub directory from given directory with an example.

Laravel 6 List All Files in Directory

There are the Following The simple About Laravel6 fetch List All Files in Directory Full Information With Example and source code.

As I will cover this Post with live Working example to develop Laravel 6 List Files and Directories with PHP, so the PHP Laravel 6: List all files in a directory is used for this example is following below.

laravel6 get list all files in directory

Using File System 1:

public function fetchFiles(Request $request)
{
    $orignal_path = public_path('upload/tamilrokers.png');
    $finalResults = File::files($orignal_path);
    dd($finalResults);
}

laravel 6 storage fetch all files in directory

Using File System 2:

public function fetchFiles(Request $request)
{
    $orignal_path = public_path('upload/tamilrokers.png');
    $finalResults = File::allfiles($orignal_path);
    dd($finalResults);

}

laravel 6 get all files in public directory

Using Storage System:

public function fetchFiles()
{
    $orignal_path = public_path('upload/tamilrokers.png');
    $finalResults = Storage::files('upload/tamilrokers.png');
    dd($finalResults);
}

get get of files in directory laravel 6

Using Storage System 2:

public function fetchFiles()
{
    $orignal_path = public_path('upload/tamilrokers.png');
    $finalResults = Storage::allfiles('upload/tamilrokers.png');
    dd($finalResults);
}

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Laravel6 get All Files in Directory using PHP Examples with demo.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.