Laravel 9 Yajra Datatables Example

Laravel 9 Yajra Datatables Tutorial

Hi Dev,

Today, This blog will provide some of the most important how to use yajra data tables in laravel 9?. The complete step by step guide of laravel 9 yajra datatables example. This Laravel 9 tutorial help to implement yajra data table with laravel 9. i will give you simple example of yajra data tables with ajax in laravel 9. In this example of how to use bootstrap data tables in laravel 9. Yajra DataTables is a jQuery plug-in which is helps us in Laravel for more functionalities like searching, sorting, pagination on tables. If you search how to use yajra data tables in laravel then here in this example is perfect implement from scratch. You have to just follow a few steps for implement data tables in your laravel application. let's start to use data tables in laravel application. Step 1: Install Laravel 9 This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel laravel-yajra-table
Step 2: Install Yajra Datatable In this step we need to install yajra datatable via the Composer package manager, so one your terminal and fire bellow command:
composer require yajra/laravel-datatables-oracle
Step 3: Add Dummy Users In this step, we will create some dummy users using tinker factory. so let's create dummy records using bellow command:
php artisan tinker
  
User::factory()->count(20)->create()
Step 4: Create Controller In this point, now we should create new controller as UserController. this controller will manage layout and getting data request and return response, so put bellow content in controller file: app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use DataTables;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = User::select('*');
            return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){
       
                            $btn = '<a href="javascript:void(0)" class="edit btn btn-success btn-sm text-center">View</a>';
      
                            return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
          
        return view('users');
    }
}
Step 5: Add Route In this is step we need to create route for datatables layout file and another one for getting data. so open your "routes/web.php" file and add following route. routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('users', [UserController::class, 'index'])->name('users.index');
Step 6: Create Blade File In Last step, let's create users.blade.php(resources/views/users.blade.php) for layout and we will write design code here and put following code: resources/views/users.blade.php
<!DOCTYPE html>
<html>
<head>
    <title> laravel 9 yajra datatables example - Itwebtuts </title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>  
    <script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.4/js/dataTables.bootstrap5.min.js"></script>
</head>
<body>
     
<div class="container">
    <h3 class="text-center mt-3 mb-4">laravel 9 yajra datatables example - Itwebtuts</h3>
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Email</th>
                <th width="100px" class="text-center">Action</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
     
</body>
     
<script type="text/javascript">
  $(function () {
      
    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('users.index') }}",
        columns: [
            {data: 'id', name: 'id'},
            {data: 'name', name: 'name'},
            {data: 'email', name: 'email'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });
      
  });
</script>
</html>
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/users
I hope it can help you...

React Native App using Stack Navigator Example

React Native App using Stack Navigator Tutorial

Hi dev,

Today, I will learn you how to use react native app using stack navigator. We will look at an example of how to implement stack navigation in react native app using stack navigator. This tutorial will give you a simple example of basics of creating a react native navigator. if you want to see an example of how to use React Navigation in your app to add navigation.

React Native is one of the most popular cross-platform app development frameworks. Using JavaScript, you can react develop native apps for both Android and iOS.

One important part of creating apps is being able to navigate between screens.

So let's start following example:

Step 1 : Project Install In the first step Run the following command for create project.
expo init stack-navigation
Step 2 : Install packages
yarn add @react-navigation/native
yarn add react-native-safe-area-context
yarn add @react-navigation/stack
expo install react-native-gesture-handler
yarn add react-native-gesture-handler
Then after add code in App.js file App.js
import 'react-native-gesture-handler';
import { StatusBar } from 'expo-status-bar';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { StyleSheet, Text, View } from 'react-native';
import HomeScreen from './screens/HomeScreen';
import ProfileScreen from './screens/ProfileScreen';

const Stack = createStackNavigator();

export default function App() {
    return (
        <NavigationContainer>
            <Stack.Navigator>
            <Stack.Screen name="Home" component={HomeScreen} />
            <Stack.Screen name="Profile Screen" component={ProfileScreen} />
            </Stack.Navigator>
        </NavigationContainer>
    );
}
screens/HomeScreen.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { StyleSheet, Text, View, Button } from 'react-native';

export default function HomeScreen({navigation}) {
    return (
        <View style={{flex: 1,alignItems: 'center', justifyContent:'center'}}>
            <Text style={{ marginBottom: '2%' }}>Home Screen / Feed</Text>
            <Button title="Profile Screen" onPress={()=>navigation.navigate('Profile Screen')} />
        </View>
    );
}
ProfileScreen.jsx
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function ProfileScreen() {
  return (
    <View style={{flex: 1,alignItems: 'center', justifyContent:'center'}}>
        <Text>Profile Screen</Text>
    </View>
  );
}
Output
React Native App using Stack Navigator Example

I hope it can help you...

Laravel 9 Ajax FullCalendar Example

Laravel 9 Ajax FullCalendar Example

Hi Dev,

In this blog, I explain laravel 9 ajax full calendar tutorial with example. I will show to you, how you can integrate a full calendar in laravel 9 application. I have written step-by-step instructions of laravel 9 FullCalendar ajax.

This comprehensive guide, step by step, explains how to add and integrate FullCalendar in Laravel not only but also how to use FullCalendar in the Laravel 9 application.

Step 1: Install Laravel 9

In this step download the new laravel application. Open your command prompt and copy paste this command:

composer create-project laravel/laravel laravel-fullcalendar
Step 2: Create Migration and Model

In this step create migration and model for events table, fire this command:

php artisan make:migration create_events_table

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create events table.

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->date('start');
            $table->date('end');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('events');
    }
};
Then after, run migration:
php artisan migrate

Now that you have created the event model, type your code into it. Copy the following model to write the code. This code you put in your Event.php model.

app/Models/Event.php
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Event extends Model
{
    use HasFactory;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array

     */
    protected $fillable = [
        'title', 'start', 'end'
    ];
}
Step 3: Create Controller File

Now require to create new FullCalenderController for index and ajax method so first run bellow command :

php artisan make:controller FullCalenderController

After this command you can find FullCalenderController.php file in your app/Http/Controllers directory. open FullCalenderController.php file and put bellow code in that file.

app/Http/Controllers/FullCalenderController.php
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Event;
  
class FullCalenderController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        if($request->ajax()) {
       
            $data = Event::whereDate('start', '>=', $request->start)
                       ->whereDate('end',   '<=', $request->end)
                       ->get(['id', 'title', 'start', 'end']);
  
            return response()->json($data);
        }
  
        return view('fullcalender');
    }
 
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function ajax(Request $request)
    {
        switch ($request->type) {
           case 'add':
                $event = Event::create([
                    'title' => $request->title,
                    'start' => $request->start,
                    'end' => $request->end,
                ]);
 
                return response()->json($event);
            break;
  
            case 'update':
                $event = Event::find($request->id)->update([
                    'title' => $request->title,
                    'start' => $request->start,
                    'end' => $request->end,
                ]);
 
                return response()->json($event);
            break;
  
            case 'delete':
                $event = Event::find($request->id)->delete();
                
                return response()->json($event);
            break;
             
            default:
            # code...
            break;
        }
    }
}
Step 4: Create Routes

In this step we will add routes and controller file so first add bellow route in your routes.php file.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\FullCalenderController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::controller(FullCalenderController::class)->group(function(){
    Route::get('fullcalender', 'index');
    Route::post('fullcalenderAjax', 'ajax');
});
Step 5: Create Blade File

Ok, in this last step we will create fullcalender.blade.php file for display fullcalender and we will write js code for crud app. So first create fullcalender.blade.php file and put bellow code:

resources/views/fullcalender.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Ajax FullCalendar Tutorial with Example - Itwebtuts</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
</head>
<body>
    
<div class="container text-center">
    <h2 class="m-5">Laravel 9 Ajax FullCalendar Tutorial with Example - Itwebtuts</h2>
    <div id='calendar'></div>
</div>
  
<script type="text/javascript">
  
$(document).ready(function () {
      
    /*------------------------------------------
    --------------------------------------------
    Get Site URL
    --------------------------------------------
    --------------------------------------------*/
    var SITEURL = "{{ url('/') }}";
    
    /*------------------------------------------
    --------------------------------------------
    CSRF Token Setup
    --------------------------------------------
    --------------------------------------------*/
    $.ajaxSetup({
        headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
      
    /*------------------------------------------
    --------------------------------------------
    FullCalender JS Code
    --------------------------------------------
    --------------------------------------------*/
    var calendar = $('#calendar').fullCalendar({
                    editable: true,
                    events: SITEURL + "/fullcalender",
                    displayEventTime: false,
                    editable: true,
                    eventRender: function (event, element, view) {
                        if (event.allDay === 'true') {
                                event.allDay = true;
                        } else {
                                event.allDay = false;
                        }
                    },
                    selectable: true,
                    selectHelper: true,
                    select: function (start, end, allDay) {
                        var title = prompt('Event Title:');
                        if (title) {
                            var start = $.fullCalendar.formatDate(start, "Y-MM-DD");
                            var end = $.fullCalendar.formatDate(end, "Y-MM-DD");
                            $.ajax({
                                url: SITEURL + "/fullcalenderAjax",
                                data: {
                                    title: title,
                                    start: start,
                                    end: end,
                                    type: 'add'
                                },
                                type: "POST",
                                success: function (data) {
                                    displayMessage("Event Created Successfully");
  
                                    calendar.fullCalendar('renderEvent',
                                        {
                                            id: data.id,
                                            title: title,
                                            start: start,
                                            end: end,
                                            allDay: allDay
                                        },true);
  
                                    calendar.fullCalendar('unselect');
                                }
                            });
                        }
                    },
                    eventDrop: function (event, delta) {
                        var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD");
                        var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD");
  
                        $.ajax({
                            url: SITEURL + '/fullcalenderAjax',
                            data: {
                                title: event.title,
                                start: start,
                                end: end,
                                id: event.id,
                                type: 'update'
                            },
                            type: "POST",
                            success: function (response) {
                                displayMessage("Event Updated Successfully");
                            }
                        });
                    },
                    eventClick: function (event) {
                        var deleteMsg = confirm("Do you really want to delete?");
                        if (deleteMsg) {
                            $.ajax({
                                type: "POST",
                                url: SITEURL + '/fullcalenderAjax',
                                data: {
                                        id: event.id,
                                        type: 'delete'
                                },
                                success: function (response) {
                                    calendar.fullCalendar('removeEvents', event.id);
                                    displayMessage("Event Deleted Successfully");
                                }
                            });
                        }
                    }
 
                });
 
    });
      
    /*------------------------------------------
    --------------------------------------------
    Toastr Success Code
    --------------------------------------------
    --------------------------------------------*/
    function displayMessage(message) {
        toastr.success(message, 'Event');
    } 
    
</script>
  
</body>
</html>
Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/fullcalender

I think you must have liked this example.....

Laravel 9 Sweet Alert Confirm Delete Tutorial

Laravel 9 Sweet Alert Confirm Delete Tutorial
Hi dev, In this blog, I am explaining laravel 9 sweet alert confirm delete example. you'll learn laravel 9 sweet alert box using data delete in the table. if you have a question about laravel 9 sweet alert then I will give a simple example with a solution. you will do the following things for laravel 9 sweet alert using record delete. Below we use sweet alert CDN to show confirm box alert before deleting any row from laravel 9 blade file. The sweet alert in any project is very important because the confirmation delete is very required to make confirm once the user is satisfied to delete your record. So the Laravel Delete with Sweetalert has been used in all projects. In this example, we will learn how to open a sweet alert before deleting a user in laravel 9 application. I will show the sweet alert jquery plugin using delete in laravel 9. I will show an easy example of a sweet alert before deleting the user in laravel 9. Let’s Delete method with Sweet Alert in Laravel 8, Laravel 7, Laravel 6, Laravel 5 easy way step by step from scratch. Step 1: Install Laravel App In this step, You can install laravel fresh app. So open the terminal and put the bellow command.
composer create-project --prefer-dist laravel/laravel laravel-sweet-alert
Step 2: Add Dummy Users In this step, we need to create add some dummy users using factory.
php artisan tinker
    
User::factory()->count(10)->create()
Step 3: Create Route In this is step we need to create some routes for add to cart function.
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('users', [UserController::class, 'index'])->name('users.index');
Route::delete('users/{id}', [UserController::class, 'delete'])->name('users.delete');
Step 4: Create Controller in this step, we need to create UserController and add following code on that file: app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use DataTables;

class UserController extends Controller
{
     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $users = User::select("*")->paginate(8);
        return view('users', compact('users'))->with('no', 1);
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function delete($id)
    {
        User::find($id)->delete();
        return back();
    }
}
Step 5: Create Blade Files here, we need to create blade files for users, products and cart page. so let's create one by one files: resources/views/users.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Sweet Alert Confirm Delete Example - Itwebtuts</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/5.0.7/sweetalert2.min.css" rel="stylesheet">
</head>
<body>
      
<div class="container">

    <h3 class="text-center mt-4 mb-5">Laravel 9 Sweet Alert Confirm Delete Example - Itwebtuts</h3>
  
    <table class="table table-bordered table-striped data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Email</th>
                <th class="text-center">Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $user)
                <tr>
                    <td>{{ $no++ }}</td>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                    <td class="text-center">
                        <form method="POST" action="{{ route('users.delete', $user->id) }}">
                            @csrf
                            <input name="_method" type="hidden" value="DELETE">
                            <button type="submit" class="btn btn-xs btn-danger btn-flat show-alert-delete-box btn-sm" data-toggle="tooltip" title='Delete'>Delete</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>
</div>
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>

<script type="text/javascript">
    $('.show-alert-delete-box').click(function(event){
        var form =  $(this).closest("form");
        var name = $(this).data("name");
        event.preventDefault();
        swal({
            title: "Are you sure you want to delete this record?",
            text: "If you delete this, it will be gone forever.",
            icon: "warning",
            type: "warning",
            buttons: ["Cancel","Yes!"],
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((willDelete) => {
            if (willDelete) {
                form.submit();
            }
        });
    });
</script>

</body>
</html>
Now we are ready to run our example so run bellow command so quick run:
php artisan serve
Now you can open bellow URL on your browser:
localhost:8000/users
I hope it can help you...

Laravel 9 Barcode Generator Tutorial

Laravel 9 Barcode Generator Tutorial
Hi dev, In this blog, I am explain laravel 9 barcode generator tutorial with example. We will use picqer/php-barcode-generator package for generating barcode in laravel 9 application. So i will use how to generate barcode in laravel 9. You will learn how to save generate bar code in laravel 9. i will Creating a basic example of picqer/php-barcode-generator laravel php. This is a picqer/php-barcode-generator is a very composer package for generate barcode in our laravel 9 app. I can simply generate any svg, png, jpg and html image of barcode. So you can easily generate any barcode by using laravel 5, laravel 6, laravel 7 , laravel 8 and laravel 9 any version easily. So let's start following example: Install Laravel 9 This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel laravel-barcode
Install picqer/php-barcode-generator In first step we will install picqer/php-barcode-generator Package that provides to generate Barcode in laravel application. So, first open your terminal and run bellow command:
composer require picqer/php-barcode-generator
1: Laravel Generate Barcode Example Here, we will create simple route for generating Barcode, Then i will show you output bellow as well: routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('barcode', function () {
  
    $generatorPNG = new Picqer\Barcode\BarcodeGeneratorPNG();
    $image = $generatorPNG->getBarcode('000005263635', $generatorPNG::TYPE_CODE_128);
  
    return response($image)->header('Content-type','image/png');
});
Output:
2: Laravel Generate Barcode and Save Example Here, we will create simple route for generating Barcode: routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('barcode-save', function () {
  
    $generatorPNG = new Picqer\Barcode\BarcodeGeneratorPNG();
    $image = $generatorPNG->getBarcode('000005263635', $generatorPNG::TYPE_CODE_128);
  
    Storage::put('barcodes/demo.png', $image);
  
    return response($image)->header('Content-type','image/png');
});
3: Laravel Generate Barcode with Blade Example Here, we will create simple route for generating Barcode, Then i will show you output bellow as well: routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('barcode-blade', function () {
  
    $generatorHTML = new Picqer\Barcode\BarcodeGeneratorHTML();
    $barcode = $generatorHTML->getBarcode('0001245259636', $generatorHTML::TYPE_CODE_128);
  
    return view('barcode', compact('barcode'));
});
resources/views/barcode.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>laravel 9 barcode generator tutorial with example - Itwebtuts</title>
</head>
<body>
    
    <h1>laravel 9 barcode generator tutorial with example - Itwebtuts</h1>
         
    <h3>Product: 1234567890</h3>  
    {!! $barcode !!}
  
</body>
</html>
I hope it can help you...

Laravel 9 Integrate Razorpay Payment Gateway Example

Hi dev,

Laravel 9 Integrate Razorpay Payment Gateway Example

In this blog, I explain you how to integrate razorpay payment gateway in laravel 9. we will learn how to integrate a razorpay payment gateway in laravel 9 application. I will share with you how to integrate Razorpay payment gateway in Laravel 9 application with example. I will share with you how to integrate Razorpay payment gateway in Laravel 9 application with example. In this Laravel 9 Razorpay Payment Gateway Integration Tutorial with Example tutorial.

In this tutorial you will learn to integrate Razorpay in laravel 9. In this step by step tutorial I’ll share laravel 9 Razorpay integration example.

Razorpay is very simple, hassle free and easy to integrate payment gateway. Integrating Razorpay payment gateway in laravel 9 is a breeze. Razorpay is one of the popular payment gateway, that allows us to accept payment from your customer.

So let's start following example:

Step 1: Install Laravel 9

In this step This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel laravel-razorpay-payment
Step 2: Create Razorpay Account

First you need to create account on razorpay. then you can easily get account key id and key secret.

Create Account from here: www.razorpay.com.

After register successfully. you need to go bellow link and get id and secret as bellow screen shot:

Go Here: https://dashboard.razorpay.com/app/keys.

Laravel 9 Integrate Razorpay Payment Gateway Example

Next you can get account key id and secret and add on .env file as like bellow:

.env
RAZORPAY_KEY=rzp_test_XXXXXXXXX
RAZORPAY_SECRET=XXXXXXXXXXXXXXXX
Step 3: Install razorpay/razorpay Package

In this step, we need to install razorpay/razorpay composer package to use razorpay api. so let's run bellow command:

composer require razorpay/razorpay
Step 4: Create Route

now we will create one route for calling our example, so let's add new route to web.php file as bellow:

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\RazorpayPaymentController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('razorpay-payment', [RazorpayPaymentController::class, 'index']);
Route::post('razorpay-payment', [RazorpayPaymentController::class, 'store'])->name('razorpay.payment.store');
Step 5: Create Controller

in this step, we will create RazorpayPaymentController and write send sms logic, so let's add new route to web.php file as bellow:

app/Http/Controllers/RazorpayPaymentController.php
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Razorpay\Api\Api;
use Session;
use Exception;
  
class RazorpayPaymentController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {        
        return view('razorpayView');
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $input = $request->all();
  
        $api = new Api(env('RAZORPAY_KEY'), env('RAZORPAY_SECRET'));
  
        $payment = $api->payment->fetch($input['razorpay_payment_id']);
  
        if(count($input)  && !empty($input['razorpay_payment_id'])) {
            try {
                $response = $api->payment->fetch($input['razorpay_payment_id'])->capture(array('amount'=>$payment['amount'])); 
  
            } catch (Exception $e) {
                return  $e->getMessage();
                Session::put('error',$e->getMessage());
                return redirect()->back();
            }
        }
          
        Session::put('success', 'Payment successful');
        return redirect()->back();
    }
}
Step 6: Create Blade File

now we need to add blade file. so let's create razorpayView.blade.php file and put bellow code:

resources/views/razorpayView.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel 9 Integrate Razorpay Payment Gateway Example - Itwebtuts</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
    <div id="app">
        <main class="py-4">
            <div class="container">
                <div class="row">
                    <div class="col-md-6 offset-3 col-md-offset-6">
  
                        @if($message = Session::get('error'))
                            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">×</span>
                                </button>
                                <strong>Error!</strong> {{ $message }}
                            </div>
                        @endif
  
                        @if($message = Session::get('success'))
                            <div class="alert alert-success alert-dismissible fade {{ Session::has('success') ? 'show' : 'in' }}" role="alert">
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">×</span>
                                </button>
                                <strong>Success!</strong> {{ $message }}
                            </div>
                        @endif
  
                        <div class="card card-default">
                            <div class="card-header">
                                Laravel - Razorpay Payment Gateway Integration
                            </div>
  
                            <div class="card-body text-center">
                                <form action="{{ route('razorpay.payment.store') }}" method="POST" >
                                    @csrf
                                    <script src="https://checkout.razorpay.com/v1/checkout.js"
                                            data-key="{{ env('RAZORPAY_KEY') }}"
                                            data-amount="1000"
                                            data-buttontext="Pay 10 INR"
                                            data-name="ItSolutionStuff.com"
                                            data-description="Rozerpay"
                                            data-image="https://www.itsolutionstuff.com/frontTheme/images/logo.png"
                                            data-prefill.name="name"
                                            data-prefill.email="email"
                                            data-theme.color="#ff7529">
                                    </script>
                                </form>
                            </div>
                        </div>
  
                    </div>
                </div>
            </div>
        </main>
    </div>
</body>
</html>
Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/razorpay-payment
Output:
Laravel 9 Integrate Razorpay Payment Gateway Tutorial

you can get testing card for razorpay from here: Click Here.

Now you can run and check.

I hope it can help you...

Laravel 9 Login with Facebook Account Tutorial

Hello dev, Today,In this tutorial. I am explain laravel 9 login with facebook account example. In this post i am going to explain about Laravel Socialite Authentication using Facebook. This post will give you simple example of laravel 9 login with facebook account. This tutorial will guide you on how to implement facebook login in laravel 9 app using socialite package. If you want to integrate Facebook login in Laravel 9 application. So for this, first you have to make an application in the Facebook Developer Console. Because when you create an app in the Facebook Developer Console. Then Facebook provides you some secret details. With the help of which you can integrate and implement Facebook login in Laravel 9 app. Facebook login implementation is very simple in Laravel 9 app using the socialite package. So you can make an app in the Facebook Developer Console by following the steps given below: Step 1: Install Laravel 9 This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel laravel-login-facebook
Step 2: Install JetStream Now, in this step, we need to use composer command to install jetstream, so let's run bellow command and install bellow library.
composer require laravel/jetstream
now, we need to create authentication using bellow command. you can create basic login, register and email verification. if you want to create team management then you have to pass addition parameter. you can see bellow commands:
php artisan jetstream:install livewire
Now, let's node js package:
npm install
let's run package:
npm run dev
now, we need to run migration command to create database table:
php artisan migrate
Step 3: Install Socialite In first step we will install Socialite Package that provide api to connect with facebook account. So, first open your terminal and run bellow command:
composer require laravel/socialite
Step 4: Create Facebook App First we need to create Facebook App and get ID and Secret. So, let's follow bellow steps as well: Step 1: Go to Facebook Developer App to click here: https://developers.facebook.com Step 2: Then click to "Create App" button as here
Step 3: Then Choose consumer here:
Step 4: Then Add App name as bellow, then after click to create app button:
Step 5: Now, you will get app id and secret, Then you need to add this details to .env file:
Step 6: If you want to upload on production then you need to specify domain as well. But, you are checking with local then you don't need to add this urls:
Now you have to set app id, secret and call back url in config file so open config/services.php and set id and secret this way: config/services.php
return [
    ....
    'facebook' => [
        'client_id' => env('FACEBOOK_CLIENT_ID'),
        'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
        'redirect' => 'http://localhost:8000/auth/facebook/callback',
    ],
]
Then you need to add google client id and client secret in .env file: .env
FACEBOOK_CLIENT_ID=xyz
FACEBOOK_CLIENT_SECRET=123
Step 5: Add Database Column In this step first we have to create migration for add facebook_id in your user table. So let's run bellow command:
php artisan make:migration add_facebook_id_column
Migration
<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('facebook_id')->nullable();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
          
    }
};
Update mode like this way: app/Models/User.php
<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
  
class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'facebook_id'
    ]; 
 
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];
  
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
  
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}
Step 6: Create Routes After adding facebook_id column first we have to add new route for facebook login. so let's add bellow route in routes.php file. routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\GoogleController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('/', function () {
    return view('welcome');
});
  
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
    return view('dashboard');
})->name('dashboard');
  
Route::controller(FacebookController::class)->group(function(){
    Route::get('auth/facebook', 'redirectToFacebook')->name('auth.facebook');
    Route::get('auth/facebook/callback', 'handleFacebookCallback');
});
Step 7: Create Controller After add route, we need to add method of facebook auth that method will handle facebook callback url and etc, first put bellow code on your FacebookController.php file.
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Exception;
  
class FacebookController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToFacebook()
    {
        return Socialite::driver('facebook')->redirect();
    }
           
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleFacebookCallback()
    {
        try {
        
            $user = Socialite::driver('facebook')->user();
         
            $finduser = User::where('facebook_id', $user->id)->first();
         
            if($finduser){
         
                Auth::login($finduser);
       
                return redirect()->intended('dashboard');
         
            }else{
                $newUser = User::updateOrCreate(['email' => $user->email],[
                        'name' => $user->name,
                        'facebook_id'=> $user->id,
                        'password' => encrypt('123456dummy')
                    ]);
        
                Auth::login($newUser);
        
                return redirect()->intended('dashboard');
            }
       
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}
Step 8: Update Blade File Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code: resources/views/auth/login.blade.php
<x-guest-layout>
    <x-jet-authentication-card>
        <x-slot name="logo">
            <x-jet-authentication-card-logo />
        </x-slot>

        <x-jet-validation-errors class="mb-4" />

        @if (session('status'))
            <div class="mb-4 font-medium text-sm text-green-600">
                {{ session('status') }}
            </div>
        @endif

        <form method="POST" action="{{ route('login') }}">
            @csrf

            <div>
                <x-jet-label for="email" value="{{ __('Email') }}" />
                <x-jet-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
            </div>

            <div class="mt-4">
                <x-jet-label for="password" value="{{ __('Password') }}" />
                <x-jet-input id="password" class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
            </div>

            <div class="block mt-4">
                <label for="remember_me" class="flex items-center">
                    <x-jet-checkbox id="remember_me" name="remember" />
                    <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
                </label>
            </div>

            <div class="flex items-center justify-end mt-4">
                @if (Route::has('password.request'))
                    <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}">
                        {{ __('Forgot your password?') }}
                    </a>
                @endif

                <x-jet-button class="ml-4">
                    {{ __('Log in') }}
                </x-jet-button>
            </div>

            <div class="flex items-center justify-center mt-4">
                <a class="btn btn-primary" href="{{ url('auth/facebook') }}" style="margin-top: 0px !important;background: blue;color: #ffffff;padding: 5px 12px;border-radius:5px;" id="btn-fblogin">
                    <i class="fa fa-facebook-square" aria-hidden="true"></i> Login with Facebook
                </a>
            </div>

        </form>
    </x-jet-authentication-card>
</x-guest-layout>
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/login
Output:
I hope it can help you...

React Native Color Picker Example Tutorial

Hi Guys, In this blog, I will explain you how to add color picker in react native. You can easily create color picker in react native. First i will import stylesheet namespace from react-native-color-picker, after I will add color picker using in react native. Here, I will give you full example for simply display color picker using react native as bellow. Step 1 - Create project In the first step Run the following command for create project.
expo init itwebtutsApp 
Step 2 - Install Package In the step,I will install npm i react-native-paper package .
yarn add react-native-color-picker
Step 3 - App.js In this step, You will open App.js file and put the code.
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { ColorPicker } from 'react-native-color-picker'

export default function App() {
  return (
    <View style={styles.container}>
      <ColorPicker
          onColorSelected={color => alert(`Color selected: ${color}`)}
          style={styles.colorpiker}
        />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 2,
    backgroundColor: '#fff',
    alignItems: 'center',
  },
  colorpiker:{
    width:350,
    height: 600,
  }
});
Step 4 - Run project In the last step run your project using bellow command.
npm start
Output
It will help you...

Laravel Create and Use Stored Procedure Example

Laravel Create and Use Stored Procedure Example

Hi Guys,

Now let's see example of how to create and use stored procedure in laravel. We will talk about laravel migration create stored procedure. you can understand a concept of how to write stored procedure in laravel.

I will give simple example with solution. you will learn how to call mysql stored procedure in laravel. In this example i will create mysql stored procedure using laravel migration and we will call stored procedure using laravel eloquent. you can easily use it with laravel 6, laravel 7 and laravel 8 version.

In this example we will create stored procedure call "get_posts_by_userid" that will return posts of given user id. so let's see bellow simple example:

Create Stored Procedure using Migration:
<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class CreatePostProcedure extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $procedure = "DROP PROCEDURE IF EXISTS `get_posts_by_userid`;
            CREATE PROCEDURE `get_posts_by_userid` (IN idx int)
            BEGIN
            SELECT * FROM posts WHERE user_id = idx;
            END;";
  
        \DB::unprepared($procedure);
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
         
    }
}
Call Stored Procedure:
Route::get('call-procedure', function () {
    $postId = 1;
    $getPost = DB::select(
       'CALL get_posts_by_userid('.$postId.')'
    );
  
    dd($getPost);
});
Output:
Array

(
    [0] => stdClass Object
        (

            [id] => 5

            [title] => Laravel 8 Image Upload Example

            [body] => Laravel 8 Image Upload Example

            [created_at] => 2021-05-01 06:00:03

            [updated_at] => 2021-05-01 06:00:03

            [user_id] => 1

        )
    [1] => stdClass Object
        (

            [id] => 6

            [title] => Laravel 8 Crud Example

            [body] => Laravel 8 Crud Example

            [created_at] => 2021-05-01 06:14:05

            [updated_at] => 2021-05-01 06:14:05

            [user_id] => 1

        )
)

It will help you....

Laravel Livewire Dependant Dropdown Tutorial

Laravel Livewire Dependant Dropdown Tutorial

Hii Guys,

Today,I learn you how to create on dependant dropdown with livewire in laravel application. I am going to do a simple laravel dependent dropdown using livewire. In this simple example through we understand how to work dependent dropdown in laravel livewire even if you beginner. you will able to create dynamic dependent dropdown in laravel livewire.

I sometimes require to make dependent dropdown like when state select at that time bellow city drop down list should change, i mean related to selected state. In this example i have two tables and there are listed bellow:

1. state 2. cities

So, when user will change state at that time, dynamically change city drop down box from database using laravel livewire. you can implement this example in your application by follow bellow few step.

Step 1 : Install Laravel App

In First step, We need to get fresh laravel version application using bellow command. So Let's open terminal and run bellow command.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Setup Database Configuration

After successfully install laravel app thenafter configure databse setup. We will open ".env" file and change the database name, username and password in the env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password
Step 3 : Create Migration and Model

In first step we have to create migration for state and cities tables using Laravel php artisan command, so first fire bellow command:

php artisan make:migration create_state_city_tables

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create tables.

database/migrations/2021_01_01_073031_create_state_city_tables.php
<?php

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

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


        Schema::create('cities', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('state_id');
            $table->string('name');
            $table->timestamps();
        });
    }

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

Now you can create State and City model for using laravel php artisan command So let's run bellow command one by one:

php artisan make:model State
php artisan make:model City

Now open model file and put the bellow code:

app/Models/State.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class State extends Model
{
    use HasFactory;
    protected $table = 'state';
    protected $fillable = ['name'];
}
app/Models/City.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    use HasFactory;
    protected $table = 'cities';
    protected $fillable = ['state_id', 'name'];
}
Step 4 : Install Livewire

In this step, You will simply install livewire to our laravel application using bellow command:

composer require livewire/livewire
Step 5 : Create Component

Now, You can create livewire component using bellow command, So Let's run bellow command to create statecity dropdown component:

php artisan make:livewire statecity 

Now they created fies on both path:

app/Http/Livewire/Statecity.php
resources/views/livewire/statecity.blade.php

Now first file we will update as bellow for Users.php file.

app/Http/Livewire/Users.php
<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\City;
use App\Models\State;

class Statecity extends Component
{
    public $states;
    public $cities;

    public $selectedState = NULL;

    public function mount()
    {
        $this->states = State::all();
        $this->cities = collect();
    }

    public function render()
    {
        return view('livewire.statecity');
    }

    public function updatedSelectedState($state)
    {
        if (!is_null($state)) {
            $this->cities = City::where('state_id', $state)->get();
        }
    }
}
Step 6 : Add Route

now, we need to add route for dynamic dependant dropdown with livewire in laravel application. so open your "routes/web.php" file and add following route.

routes/web.php
Route::view('states-city','livewire.home');
Step 7 : Create View

Here, we will create blade file for call state and city dependant dropdown route. in this file we will use @livewireStyles, @livewireScripts and @livewire('statecity'). so let's add it.

resources/views/livewire/home.blade.php

<html>
<head>
    <title>Laravel Livewire Dependant Dropdown</title>
    <script src="{{ asset('js/app.js') }}" defer></script>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    @livewireStyles
</head>
<body>
    <div class="container">
        <div class="row justify-content-center mt-5">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-dark text-white">
                        <h3>Laravel Livewire Dependant Dropdown</h3>
                    </div>
                    <div class="card-body">
                        @livewire('statecity')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
</body>
</html>
resources/views/livewire/statecity.blade.php
<div>
    <div class="form-group row">
        <label for="state" class="col-md-4 col-form-label text-md-right">State</label>

        <div class="col-md-6">
            <select wire:model="selectedState" class="form-control">
                <option value="" selected>Choose state</option>
                @foreach($states as $state)
                    <option value="{{ $state->id }}">{{ $state->name }}</option>
                @endforeach
            </select>
        </div>
    </div>

    @if (!is_null($selectedState))
        <div class="form-group row">
            <label for="city" class="col-md-4 col-form-label text-md-right">City</label>

            <div class="col-md-6">
                <select class="form-control" name="city_id">
                    <option value="" selected>Choose city</option>
                    @foreach($cities as $city)
                        <option value="{{ $city->id }}">{{ $city->name }}</option>
                    @endforeach
                </select>
            </div>
        </div>
    @endif
</div>

Now we are ready to run our example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/states-city

It will help you..

Laravel 8 Stripe Payment Gateway Integration Example

Hello Dev,

Today, I want to share about how to integrating our Laravel App with Stripe. We know that stripe is the best way to create a payment gateway system.

Stripe is a very popular and secure internet payment gateway company which helps to accept payment worldwide. Stripe provide really nice development interface to start and you don’t have to pay subscription charges to learn it provides free developer account, before starting to code in your app.

Bellow, I will give you full example for laravel 8 stripe payment gateway integration tutorial So let's follow bellow step by step.

Laravel 8 Stripe Payment Gateway Integration Example
Step 1 : Install Laravel 8

Now,In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration

In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3: Install stripe-php Package

Here,In this step we need to install stripe-php via the Composer package manager, so one your terminal and fire bellow command:

composer require cartalyst/stripe-laravel

Then configure stripe package in app.php, which is located inside config directory:

'providers' => [
 ..........
 Cartalyst\Stripe\Laravel\StripeServiceProvider::class 
],
 
'aliases' => [
 ..........
 'Stripe' => Cartalyst\Stripe\Laravel\Facades\Stripe::class 
], 
Step 4: Set Stripe API Key and SECRET
STRIPE_KEY=pk_test_xxxxxxxxxxxxxxxxxxx 
STRIPE_SECRET=sk_test_xxxxxxxxxxxxxx 

Next step, you need to set up the Stripe API key, to do this open or create the config/services.php file, and add or update the 'stripe' array:

'stripe' => [
     'secret' => env('STRIPE_SECRET'),
 ],
Step 5: Creating Payment Model & Migration

In step, run the following command on terminal to create model and migration file by using the following command:

php artisan make:model Payment -m
/database/migrations/create_payments_table.php
public function up()
{
    Schema::create('payments', function (Blueprint $table) {
        $table->id();
        $table->string('s_payment_id'); // stripe payment id
        $table->string('user_id');
        $table->string('product_id');
        $table->string('amount');
        $table->timestamps();
    });
}

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate
Step 6: Create Routes

In step, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

<?php
use App\Http\Controllers\StripePaymentController;

Route::get('stripe', [StripePaymentController::class, 'index']);
Route::post('payment-process', [StripePaymentController::class, 'process']);
Step 7: Create Controller File

In step ,I Will create stripe payment controller by using the following command:

php artisan make:controller StripePaymentController
app/Http/Controllers/StripePaymentController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Payment;
use Stripe;

class StripePaymentController extends Controller
{
    public function index()
    {
       return view('stripe');
    }

    public function process(Request $request)
    {
        $stripe = Stripe::charges()->create([
            'source' => $request->get('tokenId'),
            'currency' => 'USD',
            'amount' => $request->get('amount') * 100
        ]);
  
        return $stripe;
    }
}
Step 8: Create Blade File

In Last step, let's create stripe.blade.php(resources/views/stripe.blade.php) for layout and write code of jquery to get token from stripe here and put following code:

resources/views/stripe.blade.php
<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Laravel 8 Stripe Payment Gateway Integration Example - Nicesnippest.com</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.4.1.min.js"></script>
      <style>
         .container{
         padding: 0.5%;
         } 
      </style>
   </head>
   <body>
      <div class="container">
         <div class="row">
            <div class="col-md-12 mt-2 mb-2">
               <h3 class="text-center">Laravel 8 Payment Using Stripe Payment Gateway.</h3><hr>
            </div>            
            <div class="col-md-12 mt-2 mb-2">
               <pre id="res_token"></pre>
            </div>
         </div>
         <div class="row">
            <div class="col-md-4 offset-md-4">

                <div class="form-group">
                  <label class="label">Enter Amount</label>
                  <input type="text" name="amount" class="form-control amount">
                </div>
                <button type="button" class="btn btn-primary btn-block">Pay</button>
            </div>
         </div>
      </div>
<script src = "https://checkout.stripe.com/checkout.js" > </script> 
<script type = "text/javascript">
    $(document).ready(function() {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    });

$('.btn-block').click(function() {
  var amount = $('.amount').val();
  var handler = StripeCheckout.configure({
      key: 'pk_test_5f6jfFP2ZV5U9TXQYG0vtqFJ00eFVWNoRX', // your publisher key id
      locale: 'auto',
      token: function(token) {
          // You can access the token ID with `token.id`.
          // Get the token ID to your server-side code for use.
          $('#res_token').html(JSON.stringify(token));
          $.ajax({
              url: '{{ url("payment-process") }}',
              method: 'post',
              data: {
                  tokenId: token.id,
                  amount: amount
              },
              success: (response) => {
                  console.log(response)
              },
              error: (error) => {
                  console.log(error);
                  alert('Oops! Something went wrong')
              }
          })
      }
  });
  handler.open({
      name: 'Payment Demo',
      description: 'Itwebtuts',
      amount: amount * 100
  });
})

</script>
</body>
</html>

Now you can run using bellow command:

php artisan serve

Open bellow URL:

http://localhost:8000/stripe

Now you can check with following card details:

Name: Dev Test

Number: 4242 4242 4242 4242

CSV: 157

Expiration Month: Any Future Month

Expiration Year: Any Future Year

It will help you...

SEO Friendly Lazy Loading of Images Example

SEO Friendly Lazy Loading of Images Example

Hi Dev,

In this example,I will learn you how to implement seo friendly lazy loading of images. we will show example of seo friendly lazy loading of images. you can easyliy implement lazy loading of images.

What is Lazy Loading?

Lazy loading is an optimization technique for the online content, be it a website or a web app.

Instead of loading the entire web page and rendering it to the user in one go as in bulk loading, the concept of lazy loading assists in loading only the required section and delays the remaining, until it is needed by the user.

Here, I will give you full example for simply seo friendly lazy loading of images as bellow.

Example
<!DOCTYPE html>
<html>
<head>
  <title>SEO Friendly Lazy Loading of Images example</title>
</head>
<body>
<h1>SEO Friendly Lazy Loading of Images Example</h1>

//image-lazy
<img class="lazy-image" data-src="yourImagePath.jpg" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
    var e = [].slice.call(document.querySelectorAll("img.lazy-image"));
    if ("IntersectionObserver" in window) {
        let n = new IntersectionObserver(function (e, t) {
            e.forEach(function (e) {
                if (e.isIntersecting) {
                    let t = e.target;
                    (t.src = t.dataset.src), t.classList.remove("lazy-image"), n.unobserve(t);
                }
            });
        });
        e.forEach(function (e) {
            n.observe(e);
        });
    }
});
</script>
</body>
</html>

It will help you...

Laravel 8 Google Recaptcha V3 Example

Laravel 8 Google Recaptcha V3 Example

Hi Dev,

Today,I will learn you how to integrate google recaptcha v3 in laravel 8 application. We will talk about laravel 8 google recaptcha implement example tutorial. In this article i will show how to implement google v3 ReCAPTCHA with laravel 8 forms.

This example will give simple way to laravel implement google v3 Recaptcha tutorial, you will learn how to add google v3 Recaptcha with the contact us form in laravel 8.

Here I will give you full example for google recaptcha v3 example in laravel 8. So, let's follow few step to create example of laravel 8 google recaptcha v3 example tutorial.

Step 1 : Install Laravel 8

In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration

In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3 : Install josiasmontag/laravel-recaptchav3

In this step, we need josiasmontag/laravel-recaptchav3 package. you can install google v3 recaptcha validation package in laravel 8 google v3 recaptcha validation app. So let's open terminal and run bellow command:

composer require josiasmontag/laravel-recaptchav3

After install above package you can add providers and aliases in config file. So lets run bellow command to publish the config file:

php artisan vendor:publish --provider="Lunaweb\RecaptchaV3\Providers\RecaptchaV3ServiceProvider"

Then add the site key and secret key on .env file provided by google recaptcha website. Like following:

NOCAPTCHA_SITEKEY=secret_site_key
NOCAPTCHA_SECRET=secret_key 

If you are not register your site with google v3 recaptcha website. So, you can Click Here. And registered your site with filing simple google form.

Then you will get a google client id and secret from the google Recaptcha website.

Step 4 : Create Model and Migration

we are going to create google recaptcha v3 application for contactus. so we have to create migration for "contact_us" table and model using laravel 8 php artisan command, so first fire bellow command:

php artisan make:model ContactUs -m

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create posts table.

<?php

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

class CreateContactUsTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('contact_us', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('subject');
            $table->text('message');
            $table->timestamps();
        });
    }

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

Now you have to run this migration by following command:

php artisan migrate

Now you can add all table column in fillable So let's open model file put bellow code.

app/Models/ContactUs.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ContactUs extends Model
{
    use HasFactory;

    protected $table = 'contact_us';

    protected $fillable = ['name', 'email','subject','message'];
}
Step 5: Create Routes

Here, we need to add route for google recaptcha v3 form. so open your "routes/web.php" file and add following route.

routes/web.php
<?php
use App\Http\Controllers\GoogleV3CaptchaController;

Route::get('google-v3-recaptcha', [GoogleV3CaptchaController::class, 'index']);
Route::post('validate-g-recaptcha', [GoogleV3CaptchaController::class, 'validateGCaptch']);
Step 6: Create Controller

After add route, we need to add method of google recaptcha, first put bellow code on your GoogleController.php file

app/Http/Controllers/GoogleV3CaptchaController.php
<?php
 
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\ContactUs;
use Validator;
use Session;

class GoogleV3CaptchaController extends Controller
{
    public function index()
    {
        return view('google-v3-recaptcha');
    }
 
    public function validateGCaptch(Request $request)
    {
        $input = $request->all();

        $validator = Validator::make($input,[
            'name' => 'required',
            'email' => 'required',
            'subject' => 'required',
            'message' => 'required',
            'g-recaptcha-response' => 'required',
        ]);

        if ($validator->passes()){
            ContactUs::create($input);
            return redirect('google-v3-recaptcha')->with('status', 'Google V3 Recaptcha has been validated form');
        }

        return redirect()->back()->withErrors($validator)->withInput();
    }
}
Step 7: Create Blade File

Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code:

resources/views/google-v3-recaptcha.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>How to Use Google V3 Recaptcha Validation In Laravel 8 Form</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-4">
        @if(session('status'))
            <div class="alert alert-success">
                {{ session('status') }}
            </div>
        @endif
        <div class="card">
            <div class="card-header text-center font-weight-bold">
                <h2>Laravel 8 Contact Us - Adding Google V3 Recaptcha</h2>
            </div>
            <div class="card-body">
                <form name="g-v3-recaptcha-contact-us" id="g-v3-recaptcha-contact-us" method="post" action="{{url('validate-g-recaptcha')}}">
                    @csrf
                    <div class="form-group">
                        <label for="exampleInputEmail1">Name</label>
                        <input type="text" id="name" name="name" class="@error('name') is-invalid @enderror form-control">
                        @error('name')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>          
                    <div class="form-group">
                        <label for="exampleInputEmail1">Email</label>
                        <input type="email" id="email" name="email" class="@error('email') is-invalid @enderror form-control">
                        @error('email')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>           
                    <div class="form-group">
                        <label for="exampleInputEmail1">Subject</label>
                        <input type="text" id="subject" name="subject" class="@error('subject') is-invalid @enderror form-control">
                        @error('subject')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>      
                    <div class="form-group">
                        <label for="exampleInputEmail1">Message</label>
                        <textarea name="message" class="@error('description') is-invalid @enderror form-control"></textarea>
                        @error('message')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="form-group">
                        <input type="hidden" name="g-recaptcha-response" id="recaptcha">
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>    
    <script src="https://www.google.com/recaptcha/api.js?render={{ config('services.recaptcha.sitekey') }}"></script>
    <script>
             grecaptcha.ready(function() {
                 grecaptcha.execute('{{ config('services.recaptcha.sitekey') }}', {action: 'contact'}).then(function(token) {
                    if (token) {
                      document.getElementById('recaptcha').value = token;
                    }
                 });
             });
    </script>
    <!-- <script src="https://www.google.com/recaptcha/api.js?render={{ config('services.recaptcha.sitekey') }}"></script> -->
    
</body>
</html>

Now we are ready to run our google recaptcha v3 example with laravel 8 so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/google-v3-recaptcha

It will help you....