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

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