Laravel PhonePe Integration Example

Laravel PhonePe Integration Example

Laravel PhonePe Integration Example

In this post, we will cover the integration of PhonePe in a Laravel application, including generating a payment request and verifying the payment status.

Step 1: Set Up Your PhonePe Account

Before starting the integration, you must set up a PhonePe merchant account. Obtain your merchant ID, API key, and other necessary credentials.

Step 2: Install Required Libraries

Ensure your Laravel project is set up correctly. You might need to use packages like guzzlehttp/guzzle for making API requests:

composer require guzzlehttp/guzzle

Step 3: Configuring Your .env File

Add your PhonePe credentials to the .env file:


PHONEPE_MERCHANT_ID=your_merchant_id
PHONEPE_API_KEY=your_api_key
PHONEPE_SALT_KEY=your_salt_key
PHONEPE_BASE_URL=https://api.phonepe.com
  

Step 4: Creating the Payment Request

Create a controller to handle the payment request:


<?php

namespace App\\Http\\Controllers;

use Illuminate\\Http\\Request;
use GuzzleHttp\\Client;

class PhonePeController extends Controller
{
    public function initiatePayment(Request $request)
    {
        $amount = $request->amount * 100; // Convert to paise
        $merchantId = env('PHONEPE_MERCHANT_ID');
        $apiKey = env('PHONEPE_API_KEY');
        $saltKey = env('PHONEPE_SALT_KEY');
        $baseUrl = env('PHONEPE_BASE_URL');

        $payload = [
            'merchantId' => $merchantId,
            'transactionId' => uniqid(), // Unique transaction ID
            'amount' => $amount,
            'currency' => 'INR',
            'redirectUrl' => route('payment.callback'),
            'validity' => time() + 600, // Payment validity in seconds
        ];

        $data = json_encode($payload);
        $hashedData = hash_hmac('sha256', $data, $saltKey);

        $client = new Client();
        $response = $client->post($baseUrl . '/v3/transaction/initiate', [
            'headers' => [
                'Content-Type' => 'application/json',
                'X-VERIFY' => $hashedData . '###' . $apiKey,
            ],
            'body' => $data,
        ]);

        return response()->json(json_decode($response->getBody(), true));
    }
}
  

Step 5: Payment Callback

Create a method to handle the callback from PhonePe and verify the payment status:


<?php

namespace App\\Http\\Controllers;

use Illuminate\\Http\\Request;
use GuzzleHttp\\Client;

class PhonePeController extends Controller
{
    public function paymentCallback(Request $request)
    {
        $transactionId = $request->transactionId;
        $merchantId = env('PHONEPE_MERCHANT_ID');
        $apiKey = env('PHONEPE_API_KEY');
        $saltKey = env('PHONEPE_SALT_KEY');
        $baseUrl = env('PHONEPE_BASE_URL');

        $url = $baseUrl . "/v3/transaction/$merchantId/$transactionId/status";
        $hashedData = hash_hmac('sha256', $url, $saltKey);

        $client = new Client();
        $response = $client->get($url, [
            'headers' => [
                'X-VERIFY' => $hashedData . '###' . $apiKey,
            ],
        ]);

        $statusResponse = json_decode($response->getBody(), true);

        if ($statusResponse['success']) {
            // Payment successful
            // Update your order status or take necessary action
        } else {
            // Payment failed
        }

        return response()->json($statusResponse);
    }
}
  

Step 6: Testing

Make sure to thoroughly test the integration using test credentials provided by PhonePe. Once everything is working as expected, you can switch to live mode.

With this setup, your Laravel application can handle PhonePe payments effectively!

Laravel Google Pay Integration Example

Laravel Google Pay Integration Example

Laravel Google Pay Integration Example

In this post, we'll walk through the process of integrating Google Pay in a Laravel application.

Step 1: Install Required Packages

First, ensure your project is set up with the necessary packages. You can use the following command to install a payment gateway package like Stripe or Braintree if required:

composer require stripe/stripe-php

Step 2: Setup Google Pay in Frontend

Next, add Google Pay JavaScript in your Blade template or HTML page:

<script async src="https://pay.google.com/gp/p/js/pay.js"></script>

Step 3: Initialize Google Pay

Add the following JavaScript code to initialize Google Pay:


<script>
  const baseRequest = {
    apiVersion: 2,
    apiVersionMinor: 0
  };

  const allowedCardNetworks = ["MASTERCARD", "VISA"];
  const allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];

  const tokenizationSpecification = {
    type: 'PAYMENT_GATEWAY',
    parameters: {
      'gateway': 'stripe', // or your gateway name
      'stripe:version': '2020-08-27',
      'stripe:publishableKey': 'your-publishable-key'
    }
  };

  const cardPaymentMethod = {
    type: 'CARD',
    parameters: {
      allowedAuthMethods: allowedCardAuthMethods,
      allowedCardNetworks: allowedCardNetworks
    },
    tokenizationSpecification: tokenizationSpecification
  };

  const paymentsClient = new google.payments.api.PaymentsClient({ environment: 'TEST' });

  const paymentDataRequest = Object.assign({}, baseRequest);
  paymentDataRequest.allowedPaymentMethods = [cardPaymentMethod];
  paymentDataRequest.transactionInfo = {
    totalPriceStatus: 'FINAL',
    totalPrice: '10.00',
    currencyCode: 'USD'
  };
  paymentDataRequest.merchantInfo = {
    merchantId: 'your-merchant-id',
    merchantName: 'Your Merchant Name'
  };

  function onGooglePayLoaded() {
    paymentsClient.isReadyToPay({ allowedPaymentMethods: [cardPaymentMethod] })
      .then(function(response) {
        if (response.result) {
          createAndAddButton();
        }
      })
      .catch(function(err) {
        console.error(err);
      });
  }

  function createAndAddButton() {
    const button = paymentsClient.createButton({ onClick: onGooglePayButtonClicked });
    document.getElementById('container').appendChild(button);
  }

  function onGooglePayButtonClicked() {
    paymentsClient.loadPaymentData(paymentDataRequest)
      .then(function(paymentData) {
        // Handle payment data
        console.log(paymentData);
      })
      .catch(function(err) {
        console.error(err);
      });
  }
</script>
  

Step 4: Backend Integration

On the server side, you can use a package like stripe/stripe-php to process the payment:


<?php

namespace App\\Http\\Controllers;

use Illuminate\\Http\\Request;
use Stripe\\Stripe;
use Stripe\\Charge;

class PaymentController extends Controller
{
    public function processPayment(Request $request)
    {
        Stripe::setApiKey('your-stripe-secret-key');

        try {
            $charge = Charge::create([
                'amount' => $request->amount,
                'currency' => 'usd',
                'source' => $request->token,
                'description' => 'Payment Description'
            ]);

            return response()->json(['success' => true, 'data' => $charge]);
        } catch (\\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }
}
  

Step 5: Testing

Make sure to test your integration in the Google Pay TEST environment before switching to production.

With this setup, you have a working integration of Google Pay with Laravel!

Laravel Livewire User Active and Inactive Status Example

Laravel Livewire User Active and Inactive Status Example

Laravel Livewire User Active and Inactive Status Example

In this post, we'll walk through an example of using Laravel Livewire to toggle a user's status between active and inactive.

Setting Up the Livewire Component

First, generate a Livewire component:

php artisan make:livewire UserStatusToggle

Component Code

Here's the code for the UserStatusToggle component:


<?php

namespace App\\Http\\Livewire;

use App\\Models\\User;
use Livewire\\Component;

class UserStatusToggle extends Component
{
    public $user;

    public function toggleStatus()
    {
        $this->user->status = $this->user->status === 'active' ? 'inactive' : 'active';
        $this->user->save();
    }

    public function render()
    {
        return view('livewire.user-status-toggle');
    }
}
  

Blade View

Next, create the livewire.user-status-toggle Blade view:


<div>
    <button wire:click="toggleStatus">
        {{ $user->status === 'active' ? 'Set Inactive' : 'Set Active' }}
    </button>
</div>
  

Including Livewire in Your View

Make sure to include Livewire in your layout file:


<head>
    <!-- Other head content -->
    <livewire:styles />
</head>
<body>
    <!-- Your body content -->
    <livewire:scripts />
</body>
  

With this setup, you can easily toggle user statuses using Livewire!

Laravel Livewire Subscription Integration with Stripe

Laravel Livewire Subscription Integration with Stripe

In this tutorial, learn how to implement a subscription payment system in a Laravel application using Livewire and Stripe. We’ll cover the installation of the Stripe and Livewire packages, setting up the subscription flow, and creating views to handle the payment process. Follow these steps to add subscription functionality with Stripe in your Laravel application.

Step 1: Install Livewire and Stripe Packages

First, install Laravel Livewire and the Stripe SDK via Composer:

composer require livewire/livewire
composer require stripe/stripe-php

Step 2: Configure Stripe API Keys

Get your API keys from the Stripe Dashboard and add them to your .env file:


STRIPE_KEY=your_stripe_public_key
STRIPE_SECRET=your_stripe_secret_key

Step 3: Create a Livewire Component for Subscription

Generate a Livewire component to handle the subscription logic. Run the following command:

php artisan make:livewire SubscriptionForm

In the generated component, open app/Http/Livewire/SubscriptionForm.php and add the following code to set up Stripe's checkout session and handle subscriptions:


<?php
namespace App\Http\Livewire;

use Livewire\Component;
use Stripe\Stripe;
use Stripe\Checkout\Session;

class SubscriptionForm extends Component
{
    public $plan;

    public function mount($planId)
    {
        $this->plan = $planId;
    }

    public function createCheckoutSession()
    {
        Stripe::setApiKey(env('STRIPE_SECRET'));

        $session = Session::create([
            'payment_method_types' => ['card'],
            'line_items' => [[
                'price' => $this->plan,
                'quantity' => 1,
            ]],
            'mode' => 'subscription',
            'success_url' => route('subscription.success'),
            'cancel_url' => route('subscription.cancel'),
        ]);

        return redirect($session->url);
    }

    public function render()
    {
        return view('livewire.subscription-form');
    }
}

Step 4: Define Routes for Subscription

Define routes in your web.php file to handle the subscription process. These include routes for the checkout page, success, and cancellation:


use App\Http\Livewire\SubscriptionForm;

Route::get('/subscribe/{plan}', SubscriptionForm::class);
Route::get('/subscription/success', function () {
    return 'Subscription successful!';
})->name('subscription.success');

Route::get('/subscription/cancel', function () {
    return 'Subscription canceled.';
})->name('subscription.cancel');

Step 5: Create the Subscription Blade View

In resources/views/livewire/subscription-form.blade.php, create a view that will display a "Subscribe" button to initiate the subscription:


<div>
    <h3>Subscribe to our Plan</h3>
    <button wire:click="createCheckoutSession" class="btn btn-primary">Subscribe Now</button>
</div>

Step 6: Include Livewire Scripts

In your main layout file (e.g., resources/views/layouts/app.blade.php), include Livewire’s styles and scripts:


<head>
    ...
    <livewire:styles />
</head>

<body>
    ...
    <livewire:scripts />
</body>

Conclusion

By following these steps, you can set up a subscription payment system using Livewire and Stripe in Laravel. This integration provides a smooth, interactive subscription flow for users. Remember to test the subscription with Stripe's test mode before switching to live credentials in production.

Laravel Subscription Payment Integration with Razorpay

Laravel Subscription Payment Integration with Razorpay

Learn how to set up subscription payments in a Laravel application using Razorpay's API. This tutorial will guide you through installing Razorpay’s PHP SDK, setting up routes, and creating views to handle recurring subscription payments. Follow these steps to integrate Razorpay’s subscription feature into your Laravel project.

Step 1: Install the Razorpay PHP SDK

Start by installing the Razorpay PHP SDK via Composer:

composer require razorpay/razorpay

Step 2: Configure Razorpay API Keys

Next, get your API Key ID and API Key Secret from the Razorpay Dashboard. Add them to your .env file:


RAZORPAY_KEY_ID=your_key_id
RAZORPAY_KEY_SECRET=your_key_secret

Step 3: Create a Subscription Plan in Razorpay

In the Razorpay Dashboard, create a subscription plan with a recurring payment interval (e.g., monthly or yearly). Take note of the plan_id for this subscription, as you'll use it in your Laravel application.

Step 4: Create a Subscription Controller

Generate a controller to manage the subscription flow:

php artisan make:controller SubscriptionController

In the SubscriptionController.php, add methods to create the subscription and verify payment details. Here’s the code:


<?php
namespace App\Http\Controllers;

use Razorpay\Api\Api;
use Illuminate\Http\Request;

class SubscriptionController extends Controller
{
    private $razorpayId;
    private $razorpayKey;

    public function __construct()
    {
        $this->razorpayId = env('RAZORPAY_KEY_ID');
        $this->razorpayKey = env('RAZORPAY_KEY_SECRET');
    }

    // Create a new subscription
    public function createSubscription()
    {
        $api = new Api($this->razorpayId, $this->razorpayKey);

        $subscription = $api->subscription->create([
            'plan_id' => 'your_plan_id', // Replace with Razorpay plan ID
            'customer_notify' => 1,
            'total_count' => 12, // Number of billing cycles
        ]);

        return view('subscription.subscribe', ['subscriptionId' => $subscription->id, 'razorpayId' => $this->razorpayId]);
    }

    // Verify subscription after payment
    public function verifySubscription(Request $request)
    {
        $api = new Api($this->razorpayId, $this->razorpayKey);

        try {
            $attributes = [
                'razorpay_subscription_id' => $request->input('razorpay_subscription_id'),
                'razorpay_payment_id' => $request->input('razorpay_payment_id'),
                'razorpay_signature' => $request->input('razorpay_signature'),
            ];

            $api->utility->verifyPaymentSignature($attributes);

            return redirect('/')->with('success', 'Subscription successful.');
        } catch (\Exception $e) {
            return redirect('/')->with('error', 'Subscription verification failed.');
        }
    }
}

Step 5: Define Routes for Subscription

Add the following routes in your web.php file to handle subscription creation and verification:


use App\Http\Controllers\SubscriptionController;

Route::get('/subscribe', [SubscriptionController::class, 'createSubscription']);
Route::post('/subscribe/verify', [SubscriptionController::class, 'verifySubscription']);

Step 6: Create a Subscription View

In resources/views/subscription/subscribe.blade.php, create a Blade view to display the subscription interface:


<!DOCTYPE html>
<html>
<head>
    <title>Subscription Payment</title>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
</head>
<body>
    <h2>Subscribe to our Monthly Plan</h2>
    <button id="payButton">Subscribe Now</button>

    <script>
        document.getElementById('payButton').onclick = function () {
            var options = {
                "key": "{{ $razorpayId }}",
                "subscription_id": "{{ $subscriptionId }}",
                "name": "Your Company Name",
                "description": "Monthly Subscription",
                "handler": function (response) {
                    fetch("/subscribe/verify", {
                        method: "POST",
                        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": "{{ csrf_token() }}" },
                        body: JSON.stringify(response)
                    }).then(res => res.json())
                      .then(data => alert(data.success ? "Subscription successful!" : "Subscription failed"));
                }
            };
            var rzp1 = new Razorpay(options);
            rzp1.open();
        };
    </script>
</body>
</html>

Conclusion

With these steps, you can set up a subscription payment system in Laravel using Razorpay. Once you've tested your setup, switch to live credentials in Razorpay's dashboard to start accepting recurring payments. This integration allows you to manage subscription payments efficiently in your Laravel application.

Laravel UPI Payment Integration with Razorpay

Laravel UPI Payment Integration with Razorpay

Learn how to set up UPI payments in a Laravel application using Razorpay's API. This tutorial covers installing Razorpay's PHP SDK, setting up routes, and creating views to handle UPI transactions. Follow the steps below to get started with UPI payments in Laravel.

Step 1: Install the Razorpay PHP SDK

To begin, open your terminal and install the Razorpay PHP SDK via Composer:

composer require razorpay/razorpay

Step 2: Configure Razorpay API Keys

After installing the SDK, go to your Razorpay Dashboard and get your API Key ID and API Key Secret. Add them to your .env file:


RAZORPAY_KEY_ID=your_key_id
RAZORPAY_KEY_SECRET=your_key_secret

Step 3: Create a Payment Controller

In Laravel, create a controller to manage payment requests. Run the following Artisan command to create it:

php artisan make:controller PaymentController

Then, open PaymentController.php and add methods to initiate and verify the payment. Here’s the code for the controller:


<?php
namespace App\Http\Controllers;

use Razorpay\Api\Api;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    private $razorpayId;
    private $razorpayKey;

    public function __construct()
    {
        $this->razorpayId = env('RAZORPAY_KEY_ID');
        $this->razorpayKey = env('RAZORPAY_KEY_SECRET');
    }

    // Initiate Payment
    public function initiatePayment()
    {
        $api = new Api($this->razorpayId, $this->razorpayKey);
        $order = $api->order->create([
            'amount' => 5000, // Amount in paise (e.g., 5000 paise = ₹50)
            'currency' => 'INR',
            'payment_capture' => 1, // Auto-capture payment
        ]);

        return view('payment.initiate', ['orderId' => $order->id, 'razorpayId' => $this->razorpayId]);
    }

    // Verify Payment
    public function verifyPayment(Request $request)
    {
        $api = new Api($this->razorpayId, $this->razorpayKey);

        try {
            $attributes = [
                'razorpay_order_id' => $request->input('razorpay_order_id'),
                'razorpay_payment_id' => $request->input('razorpay_payment_id'),
                'razorpay_signature' => $request->input('razorpay_signature'),
            ];
            $api->utility->verifyPaymentSignature($attributes);
            return redirect('/')->with('success', 'Payment successful.');
        } catch (\Exception $e) {
            return redirect('/')->with('error', 'Payment verification failed.');
        }
    }
}

Step 4: Define Routes for Payment

Add the following routes in your web.php file to handle payment initiation and verification:


use App\Http\Controllers\PaymentController;

Route::get('/payment', [PaymentController::class, 'initiatePayment']);
Route::post('/payment/verify', [PaymentController::class, 'verifyPayment']);

Step 5: Create a Payment View

Create a Blade view in resources/views/payment/initiate.blade.php to display the payment interface:


<!DOCTYPE html>
<html>
<head>
    <title>UPI Payment</title>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
</head>
<body>
    <h2>Pay with UPI</h2>
    <button id="payButton">Pay ₹50 with UPI</button>

    <script>
        document.getElementById('payButton').onclick = function () {
            var options = {
                "key": "{{ $razorpayId }}",
                "amount": "5000", // Amount in paise (₹50)
                "currency": "INR",
                "name": "Your Company Name",
                "order_id": "{{ $orderId }}",
                "handler": function (response) {
                    fetch("/payment/verify", {
                        method: "POST",
                        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": "{{ csrf_token() }}" },
                        body: JSON.stringify(response)
                    }).then(res => res.json())
                      .then(data => alert(data.success ? "Payment successful!" : "Payment failed"));
                }
            };
            var rzp1 = new Razorpay(options);
            rzp1.open();
        };
    </script>
</body>
</html>

Conclusion

With these steps, you can easily set up UPI payments in Laravel using Razorpay. Once testing is complete, switch to live credentials in the Razorpay dashboard. This setup enables seamless UPI transactions in your Laravel application.

How to Send WhatsApp Messages in Laravel 11?

Hi, Guys

In this blog, I'll demonstrate how to send WhatsApp messages using the Twilio API in a Laravel 11 application.

Twilio is a cloud communications platform that provides a flexible API, allowing developers to integrate voice, messaging, and video capabilities into their applications. Renowned for its simplicity and scalability, Twilio supports multiple programming languages. Its API facilitates seamless incorporation of features like sending SMS, making voice calls, and implementing two-factor authentication. Twilio's services enable businesses to improve customer engagement and communication, offering a powerful solution for creating innovative and interactive applications across various industries.

In this example, we will use third-party package "twilio/sdk" for send whatsapp message to users. Twilio provides a WhatsApp API that allows you to send messages and media to WhatsApp users programmatically. here, we will create simple form with phone number and message box. then we will send WhatsApp message to given number. so, let's follow the following steps to done this example.

Step for Laravel WhatsApp API Integration

Step 1: Install Laravel 11

Step 2: Set up a Twilio Account

Step 3: Install twilio/sdk Package

Step 4: Create Route

Step 5: Create Controller

Step 6: Create Blade File

Run Laravel App

let's follow bellow steps:

Step 1: Install Laravel 11

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 example-app
Step 2: Set up a Twilio Account

First you need to create and add phone number. then you can easily get account SID, Token and Number.

Create Account from here: www.twilio.com.

Next add Twilio Phone Number

Next you can get account SID, Token and Number and add on .env file as like bellow:

.env
TWILIO_SID=your_twilio_account_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_WHATSAPP_NUMBER=your_twilio_whatsapp_number
Step 3: Install twilio/sdk Package

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

composer require twilio/sdk
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\WhatsAppController;
  
/*
|--------------------------------------------------------------------------
| 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('whatsapp', [WhatsAppController::class, 'index']);
Route::post('whatsapp', [WhatsAppController::class, 'store'])->name('whatsapp.post');
Step 5: Create Controller

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

app/Http/Controllers/WhatsAppController.php
<?php
  
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use Twilio\Rest\Client;
use Exception;
  
class WhatsAppController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('whatsapp');
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $twilioSid = env('TWILIO_SID');
        $twilioToken = env('TWILIO_AUTH_TOKEN');
        $twilioWhatsAppNumber = env('TWILIO_WHATSAPP_NUMBER');
        $recipientNumber = $request->phone;
        $message = $request->message;
  
        try {
            $twilio = new Client($twilioSid, $twilioToken);

            $twilio->messages->create(
                $recipientNumber,
                [
                    "from" => "whatsapp:+". $twilioWhatsAppNumber,
                    "body" => $message,
                ]
            );
  
            return back()->with(['success' => 'WhatsApp message sent successfully!']);
        } catch (Exception $e) {
            return back()->with(['error' => $e->getMessage()]);
        }
    }
}
Step 6: Create Blade File

Here, we will create "whatsapp.blade.php" file with following code:

resources/views/whatsapp.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>How to Send WhatsApp Messages in Laravel 11? - Itwebtuts.com</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
  
        <div class="row">
            <div class="col-md-9">
  
                <div class="card">
                  <div class="card-header">
                    <h2>How to Send WhatsApp Messages in Laravel 11? - Itwebtuts.com</h2>
                  </div>
                  <div class="card-body">
                    <form method="POST" action="{{ route('whatsapp.post') }}">
                
                        {{ csrf_field() }}
  
                        @if ($message = Session::get('success'))
                            <div class="alert alert-success alert-block">
                                <strong>{{ $message }}</strong>
                            </div>
                        @endif
  
                        @if ($message = Session::get('error'))
                            <div class="alert alert-danger alert-block">
                                <strong>{{ $message }}</strong>
                            </div>
                        @endif
                    
                        <div class="mb-3">
                            <label class="form-label" for="inputName">Phone:</label>
                            <input 
                                type="text" 
                                name="phone" 
                                id="inputName"
                                class="form-control @error('phone') is-invalid @enderror" 
                                placeholder="Phone Number">
              
                            @error('phone')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>
  
                        <div class="mb-3">
                            <label class="form-label" for="inputName">Message:</label>
                            <textarea 
                                name="message" 
                                id="inputName"
                                class="form-control @error('message') is-invalid @enderror" 
                                placeholder="Enter Message"></textarea>
              
                            @error('message')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>
                   
                        <div class="mb-3">
                            <button class="btn btn-success btn-submit">Send Message</button>
                        </div>
                    </form>
                  </div>
                </div>
                  
            </div>
        </div>
      
        
    </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/whatsapp
Output:

Now you can run and check.

I hope it can help you...

Laravel 11 Like Dislike System Example

Hi, Dev

In this blog, I will guide you through creating a like and dislike system in a Laravel 11 application.

In this example, we will build a like-dislike system for posts without relying on any special packages. We'll start by setting up user accounts using Laravel UI. After that, we'll create a posts table and populate it with some sample posts. We'll then create a page displaying a list of posts, each with a title and description. On this page, we'll include thumbs-up and thumbs-down icons to allow users to like or dislike the posts. We'll use AJAX to manage these like and dislike interactions seamlessly.

You can create your example by following a few steps:

Step for Laravel 11 Create Like Dislike System Example

Step 1: Install Laravel 11

Step 2: Create Posts and Likes Tables

Step 3: Create and Update Models

Step 4: Create Dummy Posts

Step 5: Create Auth using Scaffold

Step 6: Create Routes

Step 7: Create Controller

Step 8: Create and Update Blade Files

Run Laravel App Step 1: Install Laravel 11

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 example-app
Step 2: Create Posts and Likes Tables

Here, we will create posts and likes table with model. so, let's run the following command:

php artisan make:migration create_posts_table
php artisan make:migration create_likes_table

now, let's update the following migrations:

database/migrations/2024_06_11_035146_create_posts_table.php
<?php

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

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

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};
database/migrations/2024_06_13_175106_create_likes_table.php
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('likes', function (Blueprint $table) {
            $table->id();
            $table->foreignId('post_id')->constrained()->onDelete('cascade');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->boolean('like'); // true for like, false for dislike
            $table->timestamps();
        });
    }

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

now, Let's run the migration command:

php artisan migrate
Step 3: Create and Update Models

Here, we will create Post and Like model using the following command. we also need to update User model here. we will write relationship and some model function for like and dislike.

php artisan make:model Post
php artisan make:model Like

now, update the model file with hasMany() relationship:

app/Models/Post.php
<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'body'];

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function likes()
    {
        return $this->hasMany(Like::class)->where('like', true);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function dislikes()
    {
        return $this->hasMany(Like::class)->where('like', false);
    }
}
app/Models/Like.php
<?php

namespace App\Models;

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

class Like extends Model
{
    use HasFactory;

    protected $fillable = ['post_id', 'user_id', 'like'];

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
app/Models/User.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function likes()
    {
        return $this->hasMany(Like::class);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function hasLiked($postId)
    {
        return $this->likes()->where('post_id', $postId)->where('like', true)->exists();
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function hasDisliked($postId)
    {
        return $this->likes()->where('post_id', $postId)->where('like', false)->exists();
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function toggleLikeDislike($postId, $like)
    {
        // Check if the like/dislike already exists
        $existingLike = $this->likes()->where('post_id', $postId)->first();

        if ($existingLike) {
            if ($existingLike->like == $like) {
                $existingLike->delete();

                return [
                    'hasLiked' => false,
                    'hasDisliked' => false
                ];
            } else {
                $existingLike->update(['like' => $like]);
            }
        } else {
            $this->likes()->create([
                'post_id' => $postId,
                'like' => $like,
            ]);
        }

        return [
            'hasLiked' => $this->hasLiked($postId),
            'hasDisliked' => $this->hasDisliked($postId)
        ];
    }
}
Step 4: Create Dummy Posts

In this step, we need to run the migration command to create the seeder to create dummy records in posts table

Let's run the migration command:

php artisan make:seeder CreateDummyPost

noww, we need to update CreateDummyPost seeder.

database/seeders/CreateDummyPost.php
<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Post;

class CreateDummyPost extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $posts = [
            [
                'title' => 'Laravel Product CRUD Tutorial',
                'body' => 'Step by Step Laravel Product CRUD Tutorial'
            ],
            [
                'title' => 'Laravel Image Upload Example',
                'body' => 'Step by Step Laravel Image Upload Example'
            ],
            [
                'title' => 'Laravel File Upload Example',
                'body' => 'Step by Step Laravel File Upload Example'
            ],
            [
                'title' => 'Laravel Cron Job Example',
                'body' => 'Step by Step Laravel Cron Job Example'
            ],
            [
                'title' => 'Laravel Send Email Example',
                'body' => 'Step by Step Laravel Send Email Example'
            ],
            [
                'title' => 'Laravel CRUD with Image Upload',
                'body' => 'Step by Step Laravel CRUD with Image Upload'
            ],
            [
                'title' => 'Laravel Ajax CRUD with Image Upload',
                'body' => 'Step by Step Laravel Ajax CRUD with Image Upload'
            ],
            [
                'title' => 'Laravel Ajax CRUD with Image Upload',
                'body' => 'Step by Step Laravel Ajax CRUD with Image Upload'
            ]
        ];

        foreach ($posts as $key => $value) {
            Post::create([
                'title' => $value['title'],
                'body' => $value['body'],
            ]);
        }
    }
}

now, the run seeder using the following command:

php artisan db:seed --class=CreateDummyPost
Step 5: Create Auth using Scaffold

Now, in this step, we will create an auth scaffold command to generate login, register, and dashboard functionalities. So, run the following commands:

Laravel 11 UI Package:
composer require laravel/ui 
Generate Auth:
php artisan ui bootstrap --auth
npm install
npm run build
Step 6: Create Routes

In this step, we will create routes for like unlike system. So we require to create following route in web.php file.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PostController;

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

Route::middleware('auth')->group(function () {
    Route::get('posts', [PostController::class, 'index'])->name('posts.index');
    Route::post('posts/ajax-like-dislike', [PostController::class, 'ajaxLike'])->name('posts.ajax.like.dislike');
});
Step 7: Create Controller

now in PostController, we will add two new method posts() and ajaxLike(). so let's see PostController like as bellow:

app/Http/PostController.php
<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::get();
        return view('posts', compact('posts'));
    }


    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function ajaxLike(Request $request)
    {
        $post = Post::find($request->id);
        $response = auth()->user()->toggleLikeDislike($post->id, $request->like);

        return response()->json(['success' => $response]);
    }
}
Step 8: Create and Update Blade Files

In this step, we will update app.blade.php file and create posts.blade file. so, let's update it.

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">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=Nunito" rel="stylesheet">

    <!-- Scripts -->
    @vite(['resources/sass/app.scss', 'resources/js/app.js'])

    @yield('style')
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    Laravel Like DisLike System Example
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav me-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ms-auto">
                        <!-- Authentication Links -->
                        @guest
                            @if (Route::has('login'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                                </li>
                            @endif

                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                </li>
                            @endif
                        @else
                            <li class="nav-item">
                                <a class="nav-link" href="{{ route('posts.index') }}">{{ __('Posts') }}</a>
                            </li>
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }}
                                </a>

                                <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>

@yield('script')

</html>
resources/views/posts.blade.php
@extends('layouts.app')

@section('style')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style type="text/css">
    i{
        cursor: pointer;
    }
</style>
@endsection

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">{{ __('Posts List') }}</div>

                <div class="card-body">
                    
                    <div class="row">
                        @foreach($posts as $post)
                        <div class="col-md-3">
                            <div class="card mt-2" style="width: 18rem;">
                              <img src="https://picsum.photos/id/0/367/267" class="card-img-top" alt="...">
                              <div class="card-body">
                                <h5 class="card-title">{{ $post->title }}</h5>
                                <p class="card-text">Some quick example text to build on the card title and make up the bulk of the cards content.</p>
                                <div class="like-box">
                                    <i id="like-{{ $post->id }}" 
                                        data-post-id="{{ $post->id }}"
                                        class="like fa-thumbs-up {{ auth()->user()->hasLiked($post->id) ? 'fa-solid' : 'fa-regular' }}"></i> 
                                    <span class="like-count">{{ $post->likes->count() }}</span>
                                    <i id="like-{{ $post->id }}" 
                                        data-post-id="{{ $post->id }}"
                                        class="dislike fa-thumbs-down {{ auth()->user()->hasDisliked($post->id) ? 'fa-solid' : 'fa-regular' }}"></i> 
                                    <span class="dislike-count">{{ $post->dislikes->count() }}</span>
                                </div>
                              </div>
                            </div>
                        </div>
                        @endforeach
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('script')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
    $(document).ready(function() {     

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $('.like-box i').click(function(){    
            var id = $(this).attr('data-post-id');
            var boxObj = $(this).parent('div');
            var c = $(this).parent('div').find('span').text();
            var like = $(this).hasClass('like') ? 1 : 0;

            $.ajax({
               type:'POST',
               url: "{{ route('posts.ajax.like.dislike') }}",
               data:{ id:id, like:like },
               success:function(data){

                    if (data.success.hasLiked == true) {

                        if($(boxObj).find(".dislike").hasClass("fa-solid")){
                            var dislikes = $(boxObj).find(".dislike-count").text();
                            $(boxObj).find(".dislike-count").text(parseInt(dislikes)-1);
                        }

                        $(boxObj).find(".like").removeClass("fa-regular");
                        $(boxObj).find(".like").addClass("fa-solid");

                        $(boxObj).find(".dislike").removeClass("fa-solid");
                        $(boxObj).find(".dislike").addClass("fa-regular");

                        var likes = $(boxObj).find(".like-count").text();
                        $(boxObj).find(".like-count").text(parseInt(likes)+1);

                    } else if(data.success.hasDisliked == true){

                        if($(boxObj).find(".like").hasClass("fa-solid")){
                            var likes = $(boxObj).find(".like-count").text();
                            $(boxObj).find(".like-count").text(parseInt(likes)-1);
                        }

                        $(boxObj).find(".like").removeClass("fa-solid");
                        $(boxObj).find(".like").addClass("fa-regular");

                        $(boxObj).find(".dislike").removeClass("fa-regular");
                        $(boxObj).find(".dislike").addClass("fa-solid");

                        var dislike = $(boxObj).find(".dislike-count").text();
                        $(boxObj).find(".dislike-count").text(parseInt(dislike)+1);
                    } else {
                        if($(boxObj).find(".dislike").hasClass("fa-solid")){
                            var dislikes = $(boxObj).find(".dislike-count").text();
                            $(boxObj).find(".dislike-count").text(parseInt(dislikes)-1);
                        } 

                        if($(boxObj).find(".like").hasClass("fa-solid")){
                            var likes = $(boxObj).find(".like-count").text();
                            $(boxObj).find(".like-count").text(parseInt(likes)-1);
                        }

                        $(boxObj).find(".like").removeClass("fa-solid");
                        $(boxObj).find(".like").addClass("fa-regular");

                        $(boxObj).find(".dislike").removeClass("fa-solid");
                        $(boxObj).find(".dislike").addClass("fa-regular");

                    }
               }
            });

        });   

    }); 
</script>
@endsection
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/

I hope it can help you...

Laravel 11 Send Email Via Notification Example

Hi, Guys

In this blog, we will explore how to create and send email notifications in a Laravel 11 application.

Laravel notifications are a robust feature of the Laravel PHP framework, enabling you to send notifications to your users. In this article, we'll focus on sending email notifications in a Laravel 11 application.

Notifications in Laravel are managed using a notification class that extends the `Illuminate\Notifications\Notification` class. Within this class, you can define the content and format of the notification, as well as specify the channels through which it should be sent.

Laravel offers a variety of built-in channels for sending notifications, including `mail` for email notifications, `database` for storing notifications in a database, and `broadcast` for broadcasting notifications over web sockets. Additionally, you can create custom channels to send notifications through other mediums.

In this example, we will create a simple `BirthdayWish` notification to be sent to users on their birthdays. Follow the steps below to implement this example.

Step for Laravel 11 Send Email Via Notification Example

Step 1: Install Laravel 11

Step 2: Create Migration

Step 3: Update Model

Step 4: Create Notification

Step 5: Create Route

Step 6: Create Controller

Run Laravel App Step 1: Install Laravel 11

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 example-app
Step 2: Create Migration

Here, we will create a new migration to add a new column birthdate to the users table. So let's run the following command:

php artisan make:migration add_birthdate_column

After this command, you will find one file in the following path: "database/migrations". You have to put the below code in your migration file to create the products 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::table('users', function (Blueprint $table) {
            $table->date('birthdate')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        
    }
};

Now you have to run this migration by the following command:

php artisan migrate
Step 3: Update Model

In this step, we will add "birthdate" column in $fillable array.

Make sure you use Notifiable class form Illuminate\Notifications\Notifiable.

let's copy below code and paste it.

app/Models/User.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'birthdate'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}
Step 4: Create Notification

In this step, we need to create "Notification" by using the Laravel artisan command, so let's run the command below. We will create the BirthdayWish notification class.

php artisan make:notification BirthdayWish

Now you can see a new folder created as "Notifications" in the app folder. You need to make the following changes as shown in the class below.

app/Notifications/BirthdayWish.php
<?php
  
namespace App\Notifications;
  
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
  
class BirthdayWish extends Notification
{
    use Queueable;
  
    private $messages;
  
    /**
     * Create a new notification instance.
     */
    public function __construct($messages)
    {
        $this->messages = $messages;
    }
  
    /**
     * Get the notification's delivery channels.
     *
     * @return array
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }
  
    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
                    ->line($this->messages['hi'])
                    ->line($this->messages['wish'])
                    ->line('Thank you for using our application!');
    }
  
    /**
     * Get the array representation of the notification.
     *
     * @return array
     */
    public function toArray(object $notifiable): array
    {
        return [
              
        ];
    }
}

Next, you have to add the send mail configuration with mail driver, mail host, mail port, mail username, and mail password so Laravel will use those sender configurations for sending email. You can simply add it as follows:

.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Step 5: Create Route

In this step, we need to create routes for sending notifications to one user. So open your "routes/web.php" file and add the following route.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
    
Route::get('user-notify', [UserController::class, 'index']);
Step 6: Create Controller

Here, we require the creation of a new controller, UserController, with an index method to send a notification route. So let's put the code below.

app/Http/Controllers/UserController.php
<?php
   
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\User;
use App\Notifications\BirthdayWish;
    
class UserController extends Controller
{   
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $user = User::find(1);
  
        $messages["hi"] = "Hey, Happy Birthday {$user->name}";
        $messages["wish"] = "On behalf of the entire company I wish you a very happy birthday and send you my best wishes for much happiness in your life.";
          
        $user->notify(new BirthdayWish($messages));
  
        dd('Done');
    }
}
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/user-notify
Output: You Email Look Like This

I hope it can help you...

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 Join Query Example Tutorial

Hi Dev,

In this blog, i will explain Join Query in laravel. This post is focused on how to use inner join in laravel 9. We will use how to apply inner join in laravel 9. We will look at example of how to make inner join in laravel 9. In this article, we will implement a how to write inner join in laravel 9. you will do the following things for laravel 9 inner join query builder.

In this example, i will create users table and countries table. i will add country_id on users table and add countries table id on users table. so when i get users at that time we will get country name from country_id using inner join.

So, let's see bellow example:

Example users Table:
countries Table:
Laravel Query:
<?php

namespace App\Http\Controllers;

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

class JoinController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $users = User::select(
                            "users.id", 
                            "users.name",
                            "users.email", 
                            "countries.name as country_name"
                        )
                        ->join("countries", "countries.id", "=", "users.country_id")
                        ->get()
                        ->toArray();
  
        ($users);
    }

}
Output:
array:2 [▼
  0 => array:4 [▼
    "id" => 1
    "name" => "keval"
    "email" => "kevalkashiyani9@gmail.com"
    "country_name" => "india"
  ]
  1 => array:4 [▼
    "id" => 2
    "name" => "mehul"
    "email" => "mehulbagada@gmail.com"
    "country_name" => "Dubai"
  ]
]

It will help you...

Laravel 9 Livewire Auth Scaffolding using Jetstream Example

Laravel 9 Livewire Auth Scaffolding using Jetstream
Hi dev, Today, In this tutorial laravel 9 livewire auth scaffolding using jetstream. today you can visually perceive laravel 9 auth with livewire jetstream. we will avail you to give an example of laravel 9 auth with livewire tutorial. I learn simply step by step laravel 9 authentication livewire example. So, let's follow a few steps to engender an example of authentication laravel 9 livewire jetstream. Laravel 9 auth scaffolding example; In this tutorial, you will learn from scratch on how to build a login, register, logout, forget password, profile and reset password page by using scaffolding Jetstream without using laravel 9 make:auth command. Livewire provides a indite to your ajax with laravel blade, validation, etc. you can utilize a javascript framework. so you can visually perceive bellow step to engender auth utilizing laravel 9 livewire. So let's start by following an example. Install Laravel 9 here, we need to install laravel 9 application using composer command.
composer create-project laravel/laravel laravel-livewire-jetstream
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
Create Auth with Livewire: 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
  
OR
  
php artisan jetstream:install livewire --teams
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
Now, you can run and check. they installed all views, actions and all in your laravel 9 application. Laravel 9 Jetstream Features Laravel 9 Jetstream provides new all feature are configurable. you can see there is a configuration file fortify.php and jetstream.php file where you can enable and disable option for that feature: config/fortify.php
....
  
'features' => [
        Features::registration(),
        Features::resetPasswords(),
        Features::emailVerification(),
        Features::updateProfileInformation(),
        Features::updatePasswords(),
        Features::twoFactorAuthentication(),
    ],
...
config/jetstream.php
....
  
'features' => [
        Features::profilePhotos(),
        Features::api(),
        Features::teams(),
    ],
...
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/
I hope it can help you...

Laravel 9 Livewire Generate New Slug Tutorial

Laravel 9 Livewire Generate New Slug
Hi Guys, Today, This example is how to livewire generate new slug in laravel 9?. We will teach you the simple and the best way on how to generate slug in the Laravel 9 application using the livewire package. This example is short code and easy way for user. This laravel livewire create slug example, we will install a brand new laravel app, install and set up the livewire plugin, then create model, view and controllers. How to Generate Slug in Laravel with Livewire Package. So let's start following example. Step 1 - Create Fresh Laravel Project
composer create-project --prefer-dist laravel/laravel Blog
Don’t forget to get inside the app’s root:
cd Blog
Insert Database Details in ENV
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password
Step 2 - Add Livewire Library in Laravel Its easy to install the livewire package into the laravel; you have to open the terminal, type command, and execute to begin the installation process.
composer require livewire/livewire
Step 3 - Add Eloquent Sluggable Package in Laravel In the further step, you have to install the eloquent sluggable package, and this library will help you generate slug in laravel. Make sure to run the following command to install the plugin.
composer require cviebrock/eloquent-sluggable
Step 4 - Publish Sluggable Config File Now laravel slug package has been installed; now, you have to register this package for starting the creation of slugs as per the laravel eloquent models. Let us execute the command to publish the configuration file in laravel.
php artisan vendor:publish --provider="Cviebrock\EloquentSluggable\ServiceProvider"
Step 5 - Create Model and Migrations Let us create a migration and model files; theoretically, these files help in creating the table into the database. Run the below command to generate a migration and model simultaneously.
php artisan make:model Blog -m
Open app/Models/Blog.php and add the values in the newly generated models file.
<?php

namespace App\Models;

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

use Cviebrock\EloquentSluggable\Sluggable;

class Blog extends Model
{
    use HasFactory,Sluggable;

    protected $fillable = [
        'blog_title',
        'slug',
    ];

    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'blog_title'
            ]
        ];
    }
}
Open database/migrations/create_blogs_table.php and insert the table properties within the migration file.
<?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('blog_title');
            $table->string('slug');            
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
}
Now, go to console, type the recommended command to run the migration.
php artisan migrate
Step 6 - Create Route in Laravel Open the routes/web.php in this file you need to define the route.
<?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::view('/generate-slug', 'welcome');
Step 7 - Set Up Livewire Component Next, you have to execute the following command to generate the livewire blog components.
php artisan make:livewire Blogs
Eventually, the suggested command created two files on the following path:
app/Http/Livewire/Blogs.php
resources/views/livewire/blogs.blade.php
Open and update the below code in app/Http/Livewire/Blogs.php file:
<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Blog;
use \Cviebrock\EloquentSluggable\Services\SlugService;

class Blogs extends Component
{
    public $blog_title;
    public $slug;

    public function render()
    {
        $blogs = Blog::latest()->take(7)->get();
        return view('livewire.blogs', compact('blogs'));
    }

    public function generateSlug()
    {
        $this->slug = SlugService::createSlug(Blog::class, 'slug', $this->blog_title);
    }

    public function store()
    {
        Blog::create([
            'blog_title' => $this->blog_title,
            'slug'  => $this->slug
        ]);
    }    
}
Open and update the below code in resources/views/livewire/blogs.php file:
<div>
    <form wire:submit.prevent="store">
        <div class="form-group">
            <label for="blog_title" class="mb-2"><strong>Blog Title</strong></label>
            <div class="col-md-12 mb-3">
                <input wire:model="blog_title" type="text" class="form-control @error('blog_title') is-invalid @enderror" autofocus>

                @error('blog_title')
                <span class="invalid-feedback">
                    <strong>{{ $message }}</strong>
                </span>
                @enderror

            </div>
        </div>

        <div class="col-md-12">
            <div class="d-grid">
                <button type="submit" class="btn btn-dark">
                    Create Blog
                </button>
            </div>
        </div>
    </form>
    <table class="table mt-5">
        <thead>
            <tr>
                <th>Blog Title</th>
                <th>Slug</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($blogs as $blog)
            <tr>
                <td>{{ $blog->blog_title }}</td>
                <td>{{ $blog->slug }}</td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>
Step 8 - Set Up Blade View In the last step, make sure to head over to resources/views/livewire/ folder, you have to create the welcome.blade.php file in this directory and after that insert all the given below code in the suggested file: Update resources/views/livewire/welcome.blade.php file.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <title>Implement Slug in Laravel Livewire Example - Itwebtuts</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
    @livewireStyles
</head>

<body>
    <div class="container mt-3">
        @if (session()->has('message'))
        <div class="alert alert-primay">
            {{ session('message') }}
        </div>
        @endif
        @livewire('blogs')
    </div>
    @livewireScripts
</body>

</html>
Step 9 - Start Laravel App The last task is to start the laravel development server, go to terminal and run the given below command to run the app.
php artisan serve
Open your browser below url and view the app.
http://localhost:8000/generate-slug
I hope it can help you....