Showing posts sorted by date for query laravel 10. Sort by relevance Show all posts
Showing posts sorted by date for query laravel 10. Sort by relevance Show all posts

Laravel 10 Custom Forgot Password Code Tutorial

Hi Guys,

I apologize for the confusion, but the code you provided seems to be a combination of various Laravel versions and doesn't match Laravel 10. Additionally, the formatting seems to be incorrect.

Laravel 10 hasn't been released as of my knowledge cutoff in September 2021. The latest stable version is Laravel 8.x. However, I can provide you with an example of how to implement a custom forgot password functionality in Laravel 8.

Here's an example code for a custom forgot password functionality in Laravel 8:

Step 1: Create "password_resets" table migration

Create a new migration using the following command:

php artisan make:migration create_password_resets_table --create=password_resets

Then, open the generated migration file and define the table schema as follows:

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

class CreatePasswordResetsTable extends Migration
{
    public function up()
    {
        Schema::create('password_resets', function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token');
            $table->timestamp('created_at')->nullable();
        });
    }

    public function down()
    {
        Schema::dropIfExists('password_resets');
    }
}
>
Step 2: Create the ForgotPasswordController

Create a new controller using the following command:

php artisan make:controller ForgotPasswordController

Open the generated controller file and replace its contents with the following code:

<?php
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;

class ForgotPasswordController extends Controller
{
    public function showForgotPasswordForm()
    {
        return view('auth.forgot-password');
    }

    public function submitForgotPasswordForm(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
        ]);

        $status = Password::sendResetLink(
            $request->only('email')
        );

        return $status === Password::RESET_LINK_SENT
            ? back()->with('success', 'Password reset link sent!')
            : back()->withErrors(['email' => __($status)]);
    }

    public function showResetPasswordForm(Request $request)
    {
        return view('auth.reset-password', ['token' => $request->token, 'email' => $request->email]);
    }

    public function submitResetPasswordForm(Request $request)
    {
        $request->validate([
            'token' => 'required',
            'email' => 'required|email',
            'password' => 'required|min:8|confirmed',
        ]);

        $resetPasswordStatus = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function ($user, $password) {
                $user->forceFill([
                    'password' => bcrypt($password),
                    'remember_token' => Str::random(60),
                ])->save();
            }
        );

        return $resetPasswordStatus === Password::PASSWORD_RESET
            ? redirect()->route('login')->with('success', 'Password has been reset!')
            : back()->withErrors(['email' => [__($resetPasswordStatus)]]);
    }
}
?>
Step 3: Define routes

In your `routes/web.php` file, add the following routes:

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

Route::get('forgot-password', [ForgotPasswordController::class, 'showForgotPasswordForm'])
    ->name('password.request');
Route::post('forgot-password', [ForgotPasswordController::class, 'submitForgotPasswordForm'])
    ->name('password.email');
Route::get('reset-password/{token}/{email}', [ForgotPasswordController::class, 'showResetPasswordForm'])
    ->name('password.reset');
Route::post('reset-password', [ForgotPasswordController::class, 'submitResetPasswordForm'])
    ->name('password.update');
?>
Step 4: Create the views

Create the following views inside the `resources/views/auth` directory:

`forgot-password.blade.php`:

@extends('layouts.app')

@section('content')
    <div class="card">
        <div class="card-header">{{ __('Reset Password') }}</div>

        <div class="card-body">
            @if (session('status'))
                <div class="alert alert-success" role="alert">
                    {{ session('status') }}
                </div>
            @endif

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

                <div class="form-group">
                    <label for="email">{{ __('Email') }}</label>
                    <input id="email" type="email" class="form-control @error('email') is-invalid @enderror"
                           name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
                    @error('email')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                    @enderror
                </div>

                <div class="form-group mb-0">
                    <button type="submit" class="btn btn-primary">
                        {{ __('Send Password Reset Link') }}
                    </button>
                </div>
            </form>
        </div>
    </div>
@endsection

`reset-password.blade.php`:

@extends('layouts.app')

@section('content')
    <div class="card">
        <div class="card-header">{{ __('Reset Password') }}</div>

        <div class="card-body">
            <form method="POST" action="{{ route('password.update') }}">
                @csrf

                <input type="hidden" name="token" value="{{ $token }}">
                <input type="hidden" name="email" value="{{ $email }}">

                <div class="form-group">
                    <label for="password">{{ __('Password') }}</label>
                    <input id="password" type="password" class="form-control @error('password') is-invalid @enderror"
                           name="password" required autocomplete="new-password">
                    @error('password')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                    @enderror
                </div>

                <div class="form-group">
                    <label for="password-confirm">{{ __('Confirm Password') }}</label>
                    <input id="password-confirm" type="password" class="form-control" name="password_confirmation"
                           required autocomplete="new-password">
                </div>

                <div class="form-group mb-0">
                    <button type="submit" class="btn btn-primary">
                        {{ __('Reset Password') }}
                    </button>
                </div>
            </form>
        </div>
    </div>
@endsection

Make sure to have a proper layout file (`resources/views/layouts/app.blade.php`) that includes the necessary HTML structure, CSS, and JS imports.

Step 5: Update environment file

Ensure your `.env` file contains the correct mail driver configuration, such as the following:

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null

I hope it can help you...

Laravel 9 Livewire CRUD Application using JetStream Tutorial

Laravel 9 Livewire CRUD Application

Hi dev,

Laravel 9 livewire crud application using jetstream example. In this tutorial, you find a complete guide on how to make a simple crud operation app in laravel 9 using jetstream with livewire. And how to validate add & update form data on server-side in laravel 9 crud app. Laravel 9 jetstream and livewire package have made it very simple to create crud (create, read, update, delete) applications. This tutorial will give you simple example of laravel 9 livewire crud with jetstream & tailwind css. i would like to show you laravel 9 livewire crud with modal. Using this simple example of laravel 9 jetstream livewire crud app example, you can learn how to insert, read, update and delete data from the database in laravel 9. This laravel 9 livewire crud application using jetstream tutorial will implement a simple crud app in laravel 9 using jetstream with livewire and validation. Step 1 : Install Laravel9 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 --prefer-dist laravel/laravel laravel-crud-jetstream
Step 2 : Create Auth with Jetstream Livewire 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 the bellow command. you can create basic login, register, and email verification. if you want to create team management then you have to pass the 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 : Create Migration and Model Here, we need create database migration for products table and also we will create model for products table.
php artisan make:migration create_products_table
database/migrations
<?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('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
};
php artisan migrate
now we will create Product model by using following command:
php artisan make:model Product
App/Models/Product.php
<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'name', 'detail'
    ];
}
Step 4 : Create Product Component Now here we will create livewire component using their command. so run bellow command to create Product crud application component.
php artisan make:livewire products
Now they created fies on both path:
app/Http/Livewire/Products.php
resources/views/livewire/products.blade.php
Step 5 : Update Component File Here, we will write render(), create(), openModal(), closeModal(), resetInputFields(), store(), edit() and delete() method for our crud app. So, let, update following file. app/Http/Livewire/Products.php
<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Product;

class Products extends Component
{
    public $products, $name, $detail, $product_id;
    public $isOpen = 0;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
    */
    public function render()
    {
        $this->products = Product::all();
        return view('livewire.products');
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function create()
    {
        $this->resetInputFields();
        $this->openModal();
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function openModal()
    {
        $this->isOpen = true;
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function closeModal()
    {
        $this->isOpen = false;
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    private function resetInputFields(){
        $this->name = '';
        $this->detail = '';
        $this->product_id = '';
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function store()
    {
        $this->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
   
        Product::updateOrCreate(['id' => $this->product_id], [
            'name' => $this->name,
            'detail' => $this->detail
        ]);
  
        session()->flash('message', 
            $this->product_id ? 'Product Updated Successfully.' : 'Product Created Successfully.');
  
        $this->closeModal();
        $this->resetInputFields();
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function edit($id)
    {
        $product = Product::findOrFail($id);
        $this->product_id = $id;
        $this->name = $product->name;
        $this->detail = $product->detail;
    
        $this->openModal();
    }

     /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function delete($id)
    {
        Product::find($id)->delete();
        session()->flash('message', 'Product Deleted Successfully.');
    }
}
Step 6 : Update Blade Files Here, we will update following list of files for our listing page, create page. So, let's update all the files as bellow: resources/views/livewire/products.blade.php
<x-slot name="header">
    <h2 class="font-semibold text-xl text-gray-800 leading-tight text-center">
        Laravel 9 Livewire CRUD Application using JetStream Example - Itwebtuts
    </h2>
</x-slot>
<div class="py-12">
    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg px-4 py-4">
            @if (session()->has('message'))
                <div class="bg-teal-100 border-t-4 border-teal-500 rounded-b text-teal-900 px-4 py-3 shadow-md my-3" role="alert">
                  <div class="flex">
                    <div>
                      <p class="text-sm">{{ session('message') }}</p>
                    </div>
                  </div>
                </div>
            @endif
            <button wire:click="create()" class="bg-blue-500 hover:bg-blue-700 text-white py-1 mb-6 px-3 rounded my-3 mt-1">Create New Product</button>
            @if($isOpen)
                @include('livewire.create')
            @endif
            <table class="table-fixed w-full">
                <thead>
                    <tr class="bg-gray-100">
                        <th class="px-4 py-2 w-20">No.</th>
                        <th class="px-4 py-2">Title</th>
                        <th class="px-4 py-2">Body</th>
                        <th class="px-4 py-2 w-60">Action</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($products as $product)
                    <tr>
                        <td class="border px-4 py-2">{{ $product->id }}</td>
                        <td class="border px-4 py-2">{{ $product->name }}</td>
                        <td class="border px-4 py-2">{{ $product->detail }}</td>
                        <td class="border px-4 py-2 text-center">
                        <button wire:click="edit({{ $product->id }})" class="bg-blue-500 hover:bg-blue-700 text-white py-1 px-3 rounded">Edit</button>
                            <button wire:click="delete({{ $product->id }})" class="bg-red-500 hover:bg-red-700 text-white py-1 px-3 rounded">Delete</button>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>
resources/views/livewire/create.blade.php
<div class="fixed z-10 inset-0 overflow-y-auto ease-out duration-400">
  <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
      
    <div class="fixed inset-0 transition-opacity">
      <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
    </div>
  
    <!-- This element is to trick the browser into centering the modal contents. -->
    <span class="hidden sm:inline-block sm:align-middle sm:h-screen"></span>?
  
    <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full" role="dialog" aria-modal="true" aria-labelledby="modal-headline">
      <form>
      <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
        <div class="">
              <div class="mb-4">
                  <label for="exampleFormControlInput1" class="block text-gray-700 text-sm font-bold mb-2">Name:</label>
                  <input type="text" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="exampleFormControlInput1" placeholder="Enter Name" wire:model="name">
                  @error('name') <span class="text-red-500">{{ $message }}</span>@enderror
              </div>
              <div class="mb-4">
                  <label for="exampleFormControlInput2" class="block text-gray-700 text-sm font-bold mb-2">Detail:</label>
                  <textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="exampleFormControlInput2" wire:model="detail" placeholder="Enter Detail"></textarea>
                  @error('detail') <span class="text-red-500">{{ $message }}</span>@enderror
              </div>
        </div>
      </div>
  
      <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
        <span class="flex w-full rounded-md shadow-sm sm:ml-3 sm:w-auto">
          <button wire:click.prevent="store()" type="button" class="inline-flex justify-center w-full rounded-md border border-transparent px-4 py-2 bg-green-600 text-base leading-6 font-medium text-white shadow-sm hover:bg-green-500 focus:outline-none focus:border-green-700 focus:shadow-outline-green transition ease-in-out duration-150 sm:text-sm sm:leading-5">
            Save
          </button>
        </span>
        <span class="mt-3 flex w-full rounded-md shadow-sm sm:mt-0 sm:w-auto">
            
          <button wire:click="closeModal()" type="button" class="inline-flex justify-center w-full rounded-md border border-gray-300 px-4 py-2 bg-white text-base leading-6 font-medium text-gray-700 shadow-sm hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue transition ease-in-out duration-150 sm:text-sm sm:leading-5">
            Cancel
          </button>
        </span>
        </form>
      </div>
        
    </div>
  </div>
</div>
You also need to import tailwind css in your layouts.php, so let's update file: resources/views/layouts/app.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">
        <meta name="csrf-token" content="{{ csrf_token() }}">
  
        <title>{{ config('app.name', 'Laravel') }}</title>
  
        <!-- Fonts -->
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap">
  
        <!-- Styles -->
        <link rel="stylesheet" href="{{ mix('css/app.css') }}">
        <script src="https://cdn.tailwindcss.com/?plugins=forms"></script>
  
        @livewireStyles
  
        <!-- Scripts -->
        <script src="{{ mix('js/app.js') }}" defer></script>
    </head>
    <body class="font-sans antialiased">
        <x-jet-banner />
  
        <div class="min-h-screen bg-gray-100">
            @livewire('navigation-menu')
   
            <!-- Page Heading -->
            @if (isset($header))
                <header class="bg-white shadow">
                    <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
                        {{ $header }}
                    </div>
                </header>
            @endif
  
            <!-- Page Content -->
            <main>
                {{ $slot }}
            </main>
        </div>
  
        @stack('modals')
  
        @livewireScripts
    </body>
</html>
Step 7 : Add Route In third step, we will create routes for multiple file upload. so create two route with GET and POST route example. routes/web.php
<?php
   
use Illuminate\Support\Facades\Route;
   
use App\Http\Livewire\Products;
  
/*
|--------------------------------------------------------------------------
| 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('products', Products::class)->middleware('auth');
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/products
I hope it can help you...

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 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 Tailwind CSS Modal Tutorial

Laravel Tailwind CSS Modal Tutorial

Hi Dev,

Today, I will learn you how to use tailwind css modal in laravel. We will talk about laravel tailwind css modal example. In this article i will give simple button click then open modal and close button in modal for close modal.

Tailwind CSS is the only framework that I've seen scale on large teams. It’s easy to customize, adapts to any design, and the build size is tiny.

Tailwind is so low-level, it never encourages you to design the same site twice. Even with the same color palette and sizing scale, it's easy to build the same component with a completely different look in the next project.

Here I will give you full example for laravel tailwind css example so let`s see the bellow step by step:

Step 1: Install Laravel Project

In this step, you need to download the laravel fresh setup. Use this command then download laravel project setup :

composer create-project --prefer-dist laravel/laravel blog
Step 2: Install Tailwind CSS Via NPM

In this step, you need install tailwind css and tailwind css requires Node.js 12.13.0 or higher using bellow command so let's install the tailwind css.

npm install

Install Tailwind and its peer-dependencies using npm:

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
Create your configuration file

you can generate your tailwind.config.js file using bellow command:

npx tailwindcss init

This will create a minimal tailwind.config.js file at the root of your project or open this file and paste bellow code:

tailwind.config.js
module.exports = {
    purge: [
        './resources/**/*.blade.php',
        './resources/**/*.js',
        './resources/**/*.vue',
    ],
    darkMode: false, // or 'media' or 'class'
    theme: {
        extend: {},
    },
    variants: {
        extend: {},
    },
    plugins: [],
}
Step 3 : Configure Tailwind with Laravel Mix

In this step, you can configure tailwind with laravel mix and change in your webpack.mix.js, add tailwindcss as a PostCSS plugin:

mix.js("resources/js/app.js", "public/js")
    .postCss("resources/css/app.css", "public/css", [
     require("tailwindcss"),
]);
Step 4 : Include Tailwind in your CSS

Open the ./resources/css/app.css file that Laravel generates for you by default and use the @tailwind directive to include Tailwind's base, components, and utilities styles, replacing the original file contents:

resources/css/app.css
@tailwind base;
@tailwind components;
@tailwind utilities;
Step 5 : Add Route
<?php
use App\Http\Controllers\HomeController;

Route::get('/', [HomeController::class,'index']);
Step 6 : Create Controller

Here In this step, you can create new controller as HomeController so let's open terminal and bellow artisan command to create controller.

php artisan make:controller HomeController
app/Http/Controllers/HomeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

class HomeController extends Controller
{
    public function homePage()
    {
        return view('tailwind-modal');
    }
}
Step 7 : Create Blade File

In last step, You can create modal view as tailwind-modal.blade.php So let's create tailwind-modal.blade.php file and paste bellow code:

resources/views/tailwind-modal.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Tailwind CSS Modal Example</title>
    <meta charset="UTF-8" />
    <script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <button type="button" class="focus:outline-none openModal text-white text-sm py-2.5 px-5 mt-5 mx-5  rounded-md bg-green-500 hover:bg-green-600 hover:shadow-lg">Open Modal</button>
    <!-- This example requires Tailwind CSS v2.0+ -->
    <div class="fixed z-10 inset-0 invisible overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true" id="interestModal">
        <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true"></div>
                <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">​</span>
                <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                    <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                        <div class="sm:flex sm:items-start">
                            <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                                <svg @click="toggleModal" class="h-6 w-6 text-red-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                                </svg>
                            </div>
                            <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                                <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
                                  Deactivate account
                                </h3>
                            <div class="mt-2">
                                <p class="text-sm text-gray-500">
                                    Are you sure you want to deactivate your account? All of your data will be permanently removed. This action cannot be undone.
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
                        Deactivate
                    </button>
                    <button type="button" class="closeModal mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                        Cancel
                    </button>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(document).ready(function () {
            $('.openModal').on('click', function(e){
                $('#interestModal').removeClass('invisible');
            });
            $('.closeModal').on('click', function(e){
                $('#interestModal').addClass('invisible');
            });
        });
    </script>
</body>
</html>

It will help you....

Laravel Tailwind CSS Datepicker Tutorial

Laravel Tailwind CSS Datepicker

Hi Dev,

Today, I will show you how to use tailwind css datepicker in laravel. We will talk about laravel tailwind css datepicker example. In this article i will give simple datepicker using tailwind css in laravel.

Tailwind CSS is the only framework that I've seen scale on large teams. It’s easy to customize, adapts to any design, and the build size is tiny.

Tailwind is so low-level, it never encourages you to design the same site twice. Even with the same color palette and sizing scale, it's easy to build the same component with a completely different look in the next project.

Here I will give you full example for laravel tailwind css datepicker example so let;s see the bellow step by step:

Step 1: Install Laravel Project

First, you need to download the laravel fresh setup. Use this command then download laravel project setup :

composer create-project --prefer-dist laravel/laravel blog
Step 2: Install Tailwind CSS Via NPM

In this step, you need install tailwind css and tailwind css requires Node.js 12.13.0 or higher using bellow command so let's install the tailwind css.

npm install

Install Tailwind and its peer-dependencies using npm:

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
Create your configuration file

you can generate your tailwind.config.js file using bellow command:

npx tailwindcss init

This will create a minimal tailwind.config.js file at the root of your project or open this file and paste bellow code:

tailwind.config.js
module.exports = {
    purge: [
        './resources/**/*.blade.php',
        './resources/**/*.js',
        './resources/**/*.vue',
    ],
    darkMode: false, // or 'media' or 'class'
    theme: {
        extend: {},
    },
    variants: {
        extend: {},
    },
    plugins: [],
}
Step 3 : Configure Tailwind with Laravel Mix

In this step, you can configure tailwind with laravel mix and change in your webpack.mix.js, add tailwindcss as a PostCSS plugin:

mix.js("resources/js/app.js", "public/js")
    .postCss("resources/css/app.css", "public/css", [
     require("tailwindcss"),
]);
Step 4 : Include Tailwind in your CSS

Open the ./resources/css/app.css file that Laravel generates for you by default and use the @tailwind directive to include Tailwind's base, components, and utilities styles, replacing the original file contents:

resources/css/app.css
@tailwind base;
@tailwind components;
@tailwind utilities;
Step 5 : Add Route
<?php
use App\Http\Controllers\HomeController;

Route::get('/datepicker', [HomeController::class,'index']);
Step 6 : Create Controller

In this step, you can create new controller as HomeController so let's open terminal and bellow artisan command to create controller.

php artisan make:controller HomeController
app/Http/Controllers/HomeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

class HomeController extends Controller
{
    public function homePage()
    {
        return view('tailwind-datepicker');
    }
}
Step 7 : Create Blade File

In last step, You can create datepicker view as tailwind-datepicker.blade.php So let's create tailwind-datepicker.blade.php file and paste bellow code:

resources/views/tailwind-datepicker.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Tailwind CSS DatePicker Example</title>
    <meta charset="UTF-8" />
    <script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.js" defer></script>
    <style>
        [x-cloak] {
            display: none;
        }
    </style>
</head>
<body>
    <div>
    </div>
    <div class="h-screen w-screen flex  justify-center bg-gray-200 py-5">
        <div class="antialiased sans-serif mt-5">
            <h1 class="font-bold text-gray-700 text-2xl mt-5">Laravel Tailwind CSS DatePicker Example</h1>
            <div x-data="app()" x-init="[initDate(), getNoOfDays()]" x-cloak>
                <div class="container mx-auto px-4 py-2 md:py-10">
                    <div class="mb-5 w-64">
                        <label for="datepicker" class="font-bold mb-1 text-gray-700 block">Select Date</label>
                        <div class="relative">
                            <input type="hidden" name="date" x-ref="date">
                            <input 
                                type="text"
                                readonly
                                x-model="datepickerValue"
                                @click="showDatepicker = !showDatepicker"
                                @keydown.escape="showDatepicker = false"
                                class="w-full pl-4 pr-10 py-3 leading-none rounded-lg shadow-sm focus:outline-none focus:shadow-outline text-gray-600 font-medium"
                                placeholder="Select date">

                            <div class="absolute top-0 right-0 px-3 py-2">
                                <svg class="h-6 w-6 text-gray-400"  fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                                </svg>
                            </div>
                            <div  class="bg-white mt-12 rounded-lg shadow p-4 absolute top-0 left-0" style="width: 17rem" x-show.transition="showDatepicker" @click.away="showDatepicker = false">
                                <div class="flex justify-between items-center mb-2">
                                    <div>
                                        <span x-text="MONTH_NAMES[month]" class="text-lg font-bold text-gray-800"></span>
                                        <span x-text="year" class="ml-1 text-lg text-gray-600 font-normal"></span>
                                    </div>
                                    <div>
                                        <button 
                                            type="button"
                                            class="transition ease-in-out duration-100 inline-flex cursor-pointer hover:bg-gray-200 p-1 rounded-full" 
                                            :class="{'cursor-not-allowed opacity-25': month == 0 }"
                                            :disabled="month == 0 ? true : false"
                                            @click="month--; getNoOfDays()">
                                            <svg class="h-6 w-6 text-gray-500 inline-flex"  fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                                            </svg>  
                                        </button>
                                        <button 
                                            type="button"
                                            class="transition ease-in-out duration-100 inline-flex cursor-pointer hover:bg-gray-200 p-1 rounded-full" 
                                            :class="{'cursor-not-allowed opacity-25': month == 11 }"
                                            :disabled="month == 11 ? true : false"
                                            @click="month++; getNoOfDays()">
                                            <svg class="h-6 w-6 text-gray-500 inline-flex"  fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                                            </svg>                                      
                                        </button>
                                    </div>
                                </div>
                                <div class="flex flex-wrap mb-3 -mx-1">
                                    <template x-for="(day, index) in DAYS" :key="index">  
                                        <div style="width: 14.26%" class="px-1">
                                            <div
                                                x-text="day" 
                                                class="text-gray-800 font-medium text-center text-xs">
                                            </div>
                                        </div>
                                    </template>
                                </div>
                                <div class="flex flex-wrap -mx-1">
                                    <template x-for="blankday in blankdays">
                                        <div 
                                            style="width: 14.28%"
                                            class="text-center border p-1 border-transparent text-sm" 
                                        ></div>
                                    </template>   
                                    <template x-for="(date, dateIndex) in no_of_days" :key="dateIndex">   
                                        <div style="width: 14.28%" class="px-1 mb-1">
                                            <div
                                                @click="getDateValue(date)"
                                                x-text="date"
                                                class="cursor-pointer text-center text-sm leading-none rounded-full leading-loose transition ease-in-out duration-100"
                                                :class="{'bg-blue-500 text-white': isToday(date) == true, 'text-gray-700 hover:bg-blue-200': isToday(date) == false }"    
                                            ></div>
                                        </div>
                                    </template>
                                </div>
                            </div>
                        </div>     
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        const MONTH_NAMES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

        function app() {
            return {
                showDatepicker: false,
                datepickerValue: '',

                month: '',
                year: '',
                no_of_days: [],
                blankdays: [],
                days: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],

                initDate() {
                    let today = new Date();
                    this.month = today.getMonth();
                    this.year = today.getFullYear();
                    this.datepickerValue = new Date(this.year, this.month, today.getDate()).toDateString();
                },
                isToday(date) {
                    const today = new Date();
                    const d = new Date(this.year, this.month, date);

                    return today.toDateString() === d.toDateString() ? true : false;
                },
                getDateValue(date) {
                    let selectedDate = new Date(this.year, this.month, date);
                    this.datepickerValue = selectedDate.toDateString();
                    this.$refs.date.value = selectedDate.getFullYear() +"-"+ ('0'+ selectedDate.getMonth()).slice(-2) +"-"+ ('0' + selectedDate.getDate()).slice(-2);
                    console.log(this.$refs.date.value);

                    this.showDatepicker = false;
                },

                getNoOfDays() {
                    let daysInMonth = new Date(this.year, this.month + 1, 0).getDate();

                    // find where to start calendar day of week
                    let dayOfWeek = new Date(this.year, this.month).getDay();
                    let blankdaysArray = [];
                    for ( var i=1; i <= dayOfWeek; i++) {
                        blankdaysArray.push(i);
                    }

                    let daysArray = [];
                    for ( var i=1; i <= daysInMonth; i++) {
                        daysArray.push(i);
                    }

                    this.blankdays = blankdaysArray;
                    this.no_of_days = daysArray;
                }
            }
        }
    </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/datepicker

It will help you....

Laravel 8 Jetstream Livewire CRUD App Tutorial

Laravel 8 Jetstream Livewire CRUD App Tutorial

Hello Guys,

In this blog, I will learn you livewire crud with jetstream in laravel 8 application. We will learn laravel 8 jetstream livewire crud app example. I would like to share with you how perform crud opeartion livewire with jetstream in laravel 8 application.

This blog will give you easy and simple example of laravel 8 jetstream livewire crud app example. In this example i will show you step by step laravel 8 livewire crud app with modal tailwind css.

Laravel 8 jetstream designed by Tailwind CSS and they provide auth using livewire and Inertia. i will show you how to create module with livewire on default jetstream auth in laravel 8.

Here i will give you full example for laravel 8 jetstream livewire crud app example. So let's follow bellow step by step:

Step 1 : Install Laravel 8 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 : Create Jetstream Auth with Livewire:

Now, you can install jetstream using bellow command so lets open terminal and run bellow command:

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 have to need migration so let's bellow artisan command to migrate database:

php artisan migrate
Step 3 : Create Migration and Model

In this step, We have to create migration for blogs table using bellow artisan command. So let's open terminal and run bello command :

php artisan make:migration create_blogs_table
database/migrations/2020_09_26_044246_create_blogs_table.php
<?php

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

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

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

now we will create Blog model by using following command:

php artisan make:model Blog
App/Models/Blog.php
<?php

namespace App\Models;

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

class Blog extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
    */
    protected $fillable = [
        'title', 'body',
    ];
}
Step 4 : Create Blog Component

Here this step, We have to create blog livewire component using bellow command. So let's open terminal and run bello command :

php artisan make:livewire blogs

Now they created fies on both path:

app/Http/Livewire/Blogs.php
resources/views/livewire/blogs.blade.php
Step 5 : Update Component File

Here We will write render(), create(), openModal(), closeModal(), resetInputFields(), store(), edit() and delete() method for our crud app.

So, let, update following file.

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

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Blog;

class Blogs extends Component
{
   public $blogs, $title, $body, $blog_id;
    public $isOpen = 0;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function render()
    {
        $this->blogs = Blog::all();
        return view('livewire.blogs');
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function create()
    {
        $this->resetInputFields();
        $this->openModal();
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function openModal()
    {
        $this->isOpen = true;
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function closeModal()
    {
        $this->isOpen = false;
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    private function resetInputFields(){
        $this->title = '';
        $this->body = '';
        $this->blog_id = '';
    }
     
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function store()
    {
        $this->validate([
            'title' => 'required',
            'body' => 'required',
        ]);
   
        Blog::updateOrCreate(['id' => $this->blog_id], [
            'title' => $this->title,
            'body' => $this->body
        ]);
  
        session()->flash('message', 
            $this->blog_id ? 'Blog Updated Successfully.' : 'Blog Created Successfully.');
  
        $this->closeModal();
        $this->resetInputFields();
    }
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function edit($id)
    {
        $blog = Blog::findOrFail($id);
        $this->blog_id = $id;
        $this->title = $blog->title;
        $this->body = $blog->body;
    
        $this->openModal();
    }
     
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function delete($id)
    {
        Blog::find($id)->delete();
        session()->flash('message', 'Blog Deleted Successfully.');
    }
}
Step 6 : Update Blade Files

Here, we will update following list of files for our listing page, create page.

So, let, update following file.

resources/views/livewire/blogs.blade.php
<x-slot name="header">
    <h2 class="font-semibold text-xl text-gray-800 leading-tight">
        Manage blogs (Laravel 8 Jetstream Livewire CRUD App Example)
    </h2>
</x-slot>
<div class="py-12">
    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg px-4 py-4">
            @if (session()->has('message'))
                <div class="bg-teal-100 border-t-4 border-teal-500 rounded-b text-teal-900 px-4 py-3 shadow-md my-3" role="alert">
                  <div class="flex">
                    <div>
                      <p class="text-sm">{{ session('message') }}</p>
                    </div>
                  </div>
                </div>
            @endif
            <button wire:click="create()" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded my-3">Create New Blog</button>
            @if($isOpen)
                @include('livewire.create')
            @endif
            <table class="table-fixed w-full">
                <thead>
                    <tr class="bg-gray-100">
                        <th class="px-4 py-2 w-20">No.</th>
                        <th class="px-4 py-2">Title</th>
                        <th class="px-4 py-2">Body</th>
                        <th class="px-4 py-2">Action</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($blogs as $blog)
                    <tr>
                        <td class="border px-4 py-2">{{ $blog->id }}</td>
                        <td class="border px-4 py-2">{{ $blog->title }}</td>
                        <td class="border px-4 py-2">{{ $blog->body }}</td>
                        <td class="border px-4 py-2">
                        <button wire:click="edit({{ $blog->id }})" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Edit</button>
                            <button wire:click="delete({{ $blog->id }})" class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">Delete</button>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>
resources/views/livewire/create.blade.php
<div class="fixed z-10 inset-0 overflow-y-auto ease-out duration-400">
    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <!-- This element is to trick the browser into centering the modal contents. -->
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen"></span>?
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full" role="dialog" aria-modal="true" aria-labelledby="modal-headline">
            <form>
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <div class="">
                        <div class="mb-4">
                            <label for="exampleFormControlInput1" class="block text-gray-700 text-sm font-bold mb-2">Title:</label>
                            <input type="text" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="exampleFormControlInput1" placeholder="Enter Title" wire:model="title">
                            @error('title') <span class="text-red-500">{{ $message }}</span>@enderror
                        </div>
                        <div class="mb-4">
                            <label for="exampleFormControlInput2" class="block text-gray-700 text-sm font-bold mb-2">Body:</label>
                            <textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="exampleFormControlInput2" wire:model="body" placeholder="Enter Body"></textarea>
                            @error('body') <span class="text-red-500">{{ $message }}</span>@enderror
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <span class="flex w-full rounded-md shadow-sm sm:ml-3 sm:w-auto">
                        <button wire:click.prevent="store()" type="button" class="inline-flex justify-center w-full rounded-md border border-transparent px-4 py-2 bg-green-600 text-base leading-6 font-medium text-white shadow-sm hover:bg-green-500 focus:outline-none focus:border-green-700 focus:shadow-outline-green transition ease-in-out duration-150 sm:text-sm sm:leading-5">
                        Save
                        </button>
                    </span>
                    <span class="mt-3 flex w-full rounded-md shadow-sm sm:mt-0 sm:w-auto">
                        <button wire:click="closeModal()" type="button" class="inline-flex justify-center w-full rounded-md border border-gray-300 px-4 py-2 bg-white text-base leading-6 font-medium text-gray-700 shadow-sm hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue transition ease-in-out duration-150 sm:text-sm sm:leading-5">
                            Cancel
                        </button>
                    </span>
                </div>
            </form>
        </div>
    </div>
</div>
Step 7 : Add Route

In third step, we will create routes for jetstream crud with livewire .

routes/web.php
<?php
use App\Http\Livewire\Blogs;

Route::get('blog', Blogs::class);

Now we are ready to run our laravel 8 jetstream livewire crud app example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/blog

It will help you...

Laravel Custom Setter Tutorial Example

Laravel Custom Setter Tutorial Example

Hey Dev,

Today, I will learn you how to laravel custom setter tutorial in your laravel project.The laravel custom setter tutorial is so easy to use.so you can just follow my step by step and learn laravel custom setter tutorial.

So let's start to the example and follow to the my all step.

Solution
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
public function setPasswordAttribute($password)
{
    $this->attributes['password'] = bcrypt($password);
}
Step 1: Create a Employee model

Now Let's started our first step to create a Employee.php models and use this code.

Path : App/Models/Employee.php
<?php

namespace App\Models;

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

class Employee extends Model
{
    use HasFactory;

    public $table = "employee";

    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'username',
        'password',
    ];

    /**
     * Write code on Method
     *
     * @return response()
     */
     protected $hidden = [
        'password',
    ];

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }
}

Step 2: Create Route

create a route in web.php file and use this code.

Path : routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;

/*
|--------------------------------------------------------------------------
| 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('emp-create', [EmployeeController::class, 'create'])->name('emp.create');
Route::post('emp-store', [EmployeeController::class, 'store'])->name('emp.store');

Step 3: Create a EmployeeController

Next you can require to the EmployeeController so create a EmployeeController in just following command through.

php artisan make:controller EmployeeController
Path : app/Http/Controllers/EmployeeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employee;

class EmployeeController extends Controller
{

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('employee');
    }
 
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function store(Request $request)
    {

        $data = [
            'username' => $request->username,
            'password' => $request->password,
        ];

        $emp = Employee::create($data);
        dd($emp);
    }

}
Step 4: Create a employee Blade File

Next you can require to the employee.blade.php so create a employee.blade.php in your resources/views directory folder.

Path : resources/views/employee.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Custom Setters Tutorial</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body> 
   
<div class="container mt-5">
    <h1 class="text-center">Laravel Custom Setters Tutorial</h1>

    {!! Form::open(array('route' => 'emp.store','method'=>'POST')) !!}
        <div class="col-md-12">
            <div class="row mt-0">
                <div class="col-md-6">
                    <div class="form-group pl-3 pr-3">
                        <label>Username</label>
                        {{ Form::text('username', null ,['class'=>'form-control', 'placeholder'=>'User Name'] ) }}
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group pl-3 pr-3">
                        <label>Password</label>
                        {{ Form::password('password',['class'=>'form-control', 'placeholder'=>'Enter Password'] ) }}
                    </div>
                </div>
                <div class="col-md-12 text-center mt-2 mb-3">
                    <button type="submit" class="btn btn-success">Submit</button>
                </div>
            </div>
        </div>
    {!! Form::close() !!}
</div>
   
</body>
</html>

Ok, now you have to create some dummy records on employee table.

So, finally we are done with our code we can get below output.

php artisan serve
Browser url run : http://localhost:8000/emp-create
output:
App\Models\Employee {#293 ▼
  +table: "employee"
  #fillable: array:2 [▶]
  #hidden: array:1 [▶]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: true
  #attributes: array:5 [▶]
  #original: array:5 [▼
    "username" => "andy"
    "password" => "$2y$10$6PEjNQHqiVvm.3hPl64AKOlaWP.40rqL/Hobu/wy2cT.2dCvv/WQ6"
    "updated_at" => "2021-05-24 06:34:03"
    "created_at" => "2021-05-24 06:34:03"
    "id" => 8
  ]
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [▶]
}

It Will Help You...

Laravel 8 Multiple Delete Records With CheckBox Example

Laravel 8 Multiple Delete Records With CheckBox Example

Hi Guys,

In this blog, I will learn how to implement delete multiple checkbox value in laravel 8 and other version so you are just following into the my steps in step by step and learn to the laravel 8 multiple checkbox to delete value.

So, let's start to the example and follow to the my all step.

Step 1: Create laravel 8 project

First step to create a fresh laravel 8 project in using bellow command.

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

This step to configure your database details in .env file.So let's create username, password etc. So let's add.

Path : .env
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 a students table

We require students table for the store in your value and students table field to require in name and email field.so create a product table in just following command.

php artisan make:migration create_students_table
Path : database/migrations/2021_06_09_062032_create_students_table.php
<?php

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

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

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

Then next to run your migration in following command.

php artisan migrate
Step 4: create a Student model

Next we can need to the Student model so create a Student model in just following command through.

php artisan make:model Student
Path : App\Models\Product.php
<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $fillable = ['name', 'email'];
}
Step 5: create Controller

Next, in this step we need to the StudentController so create a StudentController in just following command through.

php artisan make:Controller StudentController
app/Http/Controllers/StudentController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $studentsData = Student::get();
        return view('student',compact('studentsData'));
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function destory(Request $request,$id)
    {
        $input = $request->all();
        $data = Student::find($id);
        $data->delete($id);
        return response()->json(['success'=>"Product Deleted successfully.", 'tr'=>'tr_'.$id]);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function deleteAll(Request $request)
    {   
        $ids = $request->ids;
        Student::whereIn('id',explode(',',$ids))->delete(); 
        return response()->json(['success'=>"Products Deleted successfully."]);
    }
}

Step 6: Create Routes Path : routes/web.php
<?php
use App\Http\Controllers\StudentController;
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('/', [StudentController::class, 'index']);
Route::delete('students/{id}', [StudentController::class, 'destory']);
Route::delete('studentsDeleteAll', [StudentController::class, 'deleteAll']);
Step 7: Add Blade File Path : resources/views/student.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Laravel 8 - Multiple delete records with checkbox example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-confirmation/1.0.5/bootstrap-confirmation.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style type="text/css">
        body{
            background: #fcf3f2;
        }
        table{
            background: #f2f2f2;
        }
    </style>
</head>
<body>
    <div class="container wrapper">
        <div class="row">
            <div class="col-md-10 offset-1">
                <div class="card">
                    <div class="card-header">
                        <h4>Laravel 8 - Multiple delete records with checkbox example</h4>
                        <button style="margin-bottom: 15px;" class="btn btn-warning delete_all" data-url="{{ url('studentsDeleteAll') }}">Delete All Selected</button>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-hover">
                            <tr>
                                <th width="50px"><input type="checkbox" id="master"></th>
                                <th width="80px">No.</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th width="100px">Action</th>
                            </tr>
                            @if($studentsData->count())
                                @foreach($studentsData as $key => $studentData)
                                <tr id="tr_{{ $studentData->id }}">
                                    <td><input type="checkbox" class="sub_chk" data-id="{{$studentData->id}}"></td>
                                    <td>{{ ++$key }}</td>
                                    <td>{{ $studentData->name }}</td>
                                    <td>{{ $studentData->email }}</td>
                                    <td>
                                        <a href="{{ url('students',$studentData->id) }}" class="btn btn-danger btn-sm"
                                            data-tr="tr_{{$studentData->id}}"
                                            data-toggle="confirmation"
                                            data-btn-ok-label="Delete" data-btn-ok-icon="fa fa-remove"
                                            data-btn-ok-class="btn btn-sm btn-danger"
                                            data-btn-cancel-label="Cancel"
                                            data-btn-cancel-icon="fa fa-chevron-circle-left"
                                            data-btn-cancel-class="btn btn-sm btn-default"
                                            data-title="Are you sure you want to delete ?"
                                            data-placement="left" data-singleton="true">
                                            {{-- <i class="fas fa-trash"></i> --}}
                                            Delete
                                        </a>
                                    </td>
                                </tr>
                                @endforeach
                            @endif
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

<script type="text/javascript">
    $(document).ready(function(){
        $('#master').on('click',function (e) {
            if ($(this).is(':checked',true)) {
                $('.sub_chk').prop('checked',true)
            }else {
                $('.sub_chk').prop('checked',false)
            }
        });

        $('.delete_all').on('click',function (e) {
            var allVals = [];
            $('.sub_chk:checked').each(function () {
                allVals.push($(this).attr('data-id'));
            });

            if (allVals.length <= 0) {
                alert("Please select row.");
            }else {
                var check = confirm("Are you sure you want to delete this row?");
                if (check == true) {
                    var join_selected_values = allVals.join(",");

                    $.ajax({
                        url: $(this).data('url'),
                        type: 'DELETE',
                        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                        data:'ids='+join_selected_values,
                        success:function (data) {
                            console.log(data);
                            if (data['success']) {
                                $(".sub_chk:checked").each(function () {
                                    $(this).parents("tr").remove();
                                });
                                alert(data['success']);
                            } else if (data['success']){
                                alert(data['error']);
                            } else{
                                alert('Whoops Something went wrong!!');
                            }
                        },
                        error: function (data) {
                            alert(data.responseText);
                        }
                    });

                    $.each(allVals, function( index, value ){
                        $('table tr').filter("[data-row-id='" + value + "']").remove();
                    });
                }
            }
        });

        $('[data-toggle=confirmation]').confirmation({
            rootSelector: '[data-toggle=confirmation]',
            onConfirm: function (event, element) {
                element.trigger('confirm');
            }
        });

        $(document).on('confirm', function (e) {
            var ele = e.target;
            e.preventDefault();

            $.ajax({
                url: ele.href,
                type: 'DELETE',
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                success: function (data) {
                    if (data['success']) {
                        $("#" + data['tr']).slideUp("slow");
                        alert(data['success']);
                    } else if (data['error']) {
                        alert(data['error']);
                    } else {
                        alert('Whoops Something went wrong!!');
                    }
                },
                error: function (data) {
                    alert(data.responseText);
                }
            });

            return false;
        });
    });
</script>
</html>

So, finally we are done with our code we can get below output.

Run your project in following command:

php artisan serve
Browser url run : http://localhost:8000

I Hope It Will Help You..