Skip to main content

Posts

Showing posts with the label PHP

Understanding Laravel Application Lifecycle

Laravel Lifecycle explains how a Laravel application processes a user request from the moment it enters the framework until a response is returned. Understanding the Laravel lifecycle helps developers write better controllers, middleware, service providers, and optimize application performance. What is Laravel Application Lifecycle? The Laravel lifecycle is the complete flow of a request inside a Laravel application. It starts when the web server receives a request and ends when Laravel sends a response back to the browser. The major stages of Laravel lifecycle are: Request received by the server Application bootstrapping Service container initialization Service providers registration and booting Request routing Middleware execution Controller execution Response generation Step 1: Request Enters Laravel Application Every Laravel request starts from the public/index.php file. This is the entry point of every Laravel application. p...

How to Generate a PDF File in Laravel Using DomPDF

How to Generate a PDF File in Laravel Using DomPDF Generating PDF files is a common requirement in modern web applications. Whether you need invoices, reports, or downloadable documents, Laravel makes this task simple with the help of the DomPDF library. In this tutorial, we will walk through the complete process of generating a PDF file in Laravel using DomPDF. What is DomPDF? DomPDF is a PHP library that converts HTML and CSS into PDF documents. It is lightweight, easy to use, and integrates seamlessly with Laravel. By writing standard HTML and CSS, you can quickly create professional-looking PDFs. Step 1: Install DomPDF in Laravel The easiest way to install DomPDF in Laravel is via Composer. Run the following command in your project directory: composer require barryvdh/laravel-dompdf Laravel will a...

How to Setup MongoDB with Laravel

How to Setup MongoDB with Laravel (Quick Guide) In modern web applications, developers often look for flexible and scalable database solutions — and that’s where MongoDB shines. Unlike traditional SQL databases, MongoDB stores data in a document-oriented format, making it ideal for projects that handle dynamic, unstructured, or rapidly evolving data. Integrating it with Laravel allows you to enjoy the power of MongoDB’s flexibility while still using Laravel’s elegant and expressive syntax. This step-by-step guide walks you through the complete process of integrating MongoDB with a Laravel application using the official mongodb/laravel-mongodb package. You’ll learn how to install all required dependencies, properly configure your .env and database settings, and seamlessly perform basic CRUD (Create, Read, Update, Delete) operations with MongoDB — all while maintaining Larav...

How to Remove a Package from Laravel using Composer (Step-by-Step Guide)

How to Remove a Package from Laravel using Composer (Step-by-Step Guide) When working with Laravel , you often install multiple Composer packages to extend functionality. But what if you no longer need one? In this guide, you’ll learn the correct way to remove a package from Laravel using Composer — safely and cleanly. Step 1: Identify the Package Name To begin, open your composer.json file or run the following command in your Laravel project root: composer show This lists all installed Composer packages. Find the exact name of the one you want to remove — for example, barryvdh/laravel-debugbar . Step 2: Remove the Package Use the composer remove command to uninstall it: composer remove barryvdh/laravel-debugbar This command will: Uninstall the package from your Laravel project. Update the composer.json and composer.lock files. Automatically clean up the...

How to Set Up & Use Laravel Telescope

How to Set Up & Use Laravel Telescope Laravel Telescope is a powerful debugging and monitoring tool built by the Laravel team. It provides detailed insights into your application’s requests, exceptions, database queries, jobs, mail, notifications, cache, and more—all in an elegant dashboard. 🚀 What is Laravel Telescope? Laravel Telescope acts as a “developer’s black box,” recording everything that happens within your Laravel app. It’s especially useful during development and staging to track performance issues, failed jobs, or unexpected behavior. 🧩 Step 1: Install Telescope Run the following Composer command in your Laravel project directory: composer require laravel/telescope --dev The --dev flag ensures Telescope is only installed in your local development environment. ⚙️ Step 2: Publish Telescope Assets Once the package is installed, publish the Telescope service provider and assets: php artisan tel...

Difference Between Service Provider & Service Container in Laravel

Difference Between Service Provider & Service Container in Laravel In Laravel, two important concepts are Service Container and Service Provider . They work hand in hand to make your code clean, testable, and flexible. If you’re new to Laravel, don’t worry — let’s break it down step by step with simple examples. 1. What is the Service Container? The Service Container is the heart of Laravel’s dependency injection system . It’s basically a container (or box) that holds all the classes, objects, and services your application might need. Think of the Service Container as a toolbox . Whenever your code asks for a “tool” (a class or service), Laravel looks inside the toolbox and gives it to you. Example: // Binding a class in the container app()->bind('PaymentGateway', function () { return new \App\Services\PayPalPayment(); }); // Resolving it later $payment = app()->make('PaymentG...

How to Write Cronjob in Laravel

How to Write Cronjob in Laravel Automating repetitive tasks is essential in modern web applications. Laravel provides a powerful Task Scheduling feature that makes it easy to define and manage cron jobs directly from your application. In this guide, we’ll walk through the process of writing and scheduling a cron job in Laravel. Step 1: Create a New Artisan Command Laravel’s make:command Artisan command allows you to generate custom console commands that can be scheduled as cron jobs. php artisan make:command SendReportCommand This will create a new file inside app/Console/Commands/SendReportCommand.php . Step 2: Define the Command Logic Open the generated command file and add your desired logic in the handle() method. namespace App\Console\Commands; use Illuminate\Console\Command; class SendReportCommand extends Command { // Command signature (used when calling the command) protec...

How to Use Laravel with Subdomains on cPanel

How to Use Laravel with Subdomains on cPanel Laravel supports subdomain routing out of the box, but configuring it on cPanel can be confusing for new developers. Whether you're building a multi-tenant app or organizing admin panels, here's how to properly set up subdomains with Laravel on shared hosting. 🛠️ Prerequisites Laravel project deployed on a cPanel-hosted domain Access to the Subdomains section in cPanel Basic knowledge of Laravel routing 🌐 Step 1: Create Subdomains in cPanel Log in to your cPanel account. Go to Subdomains under the Domains section. Create a subdomain like admin.example.com . Point the document root to your Laravel project’s public/ directory. For example: /home/your-user/your-laravel-project/public Repeat for each subdomain (e.g. user.example.com ). 🧭 Step 2: Define Subdomain Routes in Laravel In your Larav...

Laravel Queue Setup on Shared Hosting

Laravel Queue Setup on Shared Hosting Laravel queues allow you to defer time-consuming tasks like sending emails or processing uploads. But on shared hosting, there’s no supervisor tool like on VPS. Don’t worry — with cPanel and cron, you can still run queues efficiently. 🛠️ Prerequisites Laravel project already deployed on shared hosting (via cPanel) Queueable jobs created using php artisan make:job Basic understanding of Laravel's queue system ⚙️ Step 1: Configure Your Laravel Queue By default, Laravel uses the sync driver, which runs jobs immediately. Update the driver to database (or Redis, if supported): QUEUE_CONNECTION=database In your .env file, set the queue driver. If using database , run: php artisan queue:table && php artisan migrate This creates the necessary table for storing queued jobs. 📍 Step 2: Locate the Laravel Project Path Find your full La...

How to Schedule Cron Jobs in Laravel on cPanel

How to Schedule Cron Jobs in Laravel on cPanel Laravel's task scheduler makes it easy to automate repetitive tasks like sending emails or cleaning up logs. On shared hosting with cPanel , you can trigger Laravel's scheduler using cron jobs. In this post, I’ll guide you through setting it up step by step. 🛠️ Prerequisites Laravel project already deployed on cPanel Access to cPanel's Cron Jobs section Basic knowledge of Laravel commands 📄 Step 1: Create Your Laravel Scheduled Tasks Define your scheduled tasks inside the app/Console/Kernel.php file under the schedule() method: protected function schedule(Schedule $schedule) { $schedule->command('emails:send')->daily(); $schedule->command('backup:run')->weekly(); } You can schedule Artisan commands, closures, queue jobs, and more. 📍 Step 2: Locate the Laravel Project Path Find the absolute...

How to Upload a PHP/Laravel Project on cPanel

How to Upload a PHP/Laravel Project on cPanel Deploying a Laravel project on cPanel can seem tricky, especially if you're coming from a local development environment. But don’t worry — in this post, I’ll walk you through every step to make your Laravel application live on shared hosting via cPanel. 🛠️ Prerequisites Laravel project ready on your local machine cPanel access with PHP 8.0+ support Access to MySQL via phpMyAdmin 📁 Step 1: Prepare Your Laravel Project Run composer install --optimize-autoloader --no-dev to install only production dependencies. Run php artisan config:cache and php artisan route:cache . Zip the entire Laravel project. 📤 Step 2: Upload Project to cPanel Login to your cPanel account. Open File Manager . Navigate to the public_html directory. Upload your Laravel zip file and extract it. 🔄 Step 3: Move Folde...

20 Laravel Tips Every Developer Should Know (But Commonly Overlooked)

20 Laravel Tips Every Developer Should Know (But Commonly Overlooked) Laravel is powerful, elegant, and developer-friendly—but many of its gems remain hidden or underused. Here are 20 Laravel tips and features that you might not be using yet but definitely should. 1. Eloquent Accessors & Mutators Format your model's attributes when retrieving ( Accessor ) or setting ( Mutator ) them. public function getNameAttribute($value) { return ucfirst($value); } 2. Route Model Binding Let Laravel automatically inject models into routes, making code cleaner and error-free. Route::get('/user/{user}', function(User $user) { return $user; }); 3. $fillable and $guarded Control which fields can be mass assigned to prevent mass assignment vulnerabilities. 4. Query Builder’s when() Method Build clean conditional queries without unnecessary if-else blocks. 5. Blade Directives: @isset, @empty, @auth Make your B...

How to Use Debugger in Laravel – A Complete Guide

How to Use Debugger in Laravel – A Complete Guide Debugging is an essential part of development. Laravel provides multiple tools and techniques to help you find and fix issues faster. In this guide, you’ll learn how to effectively use Laravel Debugbar, Xdebug, and built-in debugging functions. 🔧 1. Using Laravel Debugbar Laravel Debugbar is a developer toolbar that shows request details, queries, memory usage, and much more in your browser. 👉 Step 1: Install Debugbar composer require barryvdh/laravel-debugbar --dev 👉 Step 2: Publish the config (optional) php artisan vendor:publish --provider="Barryvdh\Debugbar\ServiceProvider" ✅ Features: Query log with time Request and response headers Route info Auth info Rendered views Memory usage and performance After installation, visit any Laravel page and you'll see a Debugbar at the bottom of your browser with useful debug informa...

How to Use Rate Limiting in Laravel

How to Use Rate Limiting in Laravel Rate limiting is a crucial security and performance feature that helps prevent abuse, brute-force attacks, and overuse of your application resources. Laravel provides a powerful and flexible way to handle rate limiting via built-in middleware and custom configurations. 🚧 Why Use Rate Limiting? Protect endpoints from spamming or brute-force login attempts Ensure fair use of server resources Improve overall API and application performance ⚙️ Using Laravel's Built-in Throttle Middleware Laravel includes a throttle middleware you can apply to routes or route groups. Route::middleware('throttle:60,1')->group(function () { Route::get('/api/data', 'ApiController@getData'); }); This allows a maximum of 60 requests per minute per IP address. 🛠️ Creating Custom Rate Limiters Since Laravel 8, you can define named rate limiters using the RateLimiter facade ...

How to Integrate RevenueCat Webhook in Laravel

How to Integrate RevenueCat Webhook in Laravel If you're using RevenueCat to manage in-app subscriptions for your mobile app (iOS, Android, etc.), it’s important to connect it with your backend. Laravel makes it easy to handle incoming webhooks for real-time events like purchases, renewals, cancellations, and more. 📌 What is RevenueCat? RevenueCat is a powerful subscription management platform for mobile apps. It simplifies in-app purchases across iOS, Android, and Stripe. With webhooks, it notifies your server in real-time when important events happen, such as a new purchase or a cancellation. 🔗 Webhook Events from RevenueCat Common webhook events include: INITIAL_PURCHASE RENEWAL CANCELLATION BILLING_ISSUE EXPIRATION SUBSCRIBER_ALIAS 🔗 For a full list of event payloads, visit: RevenueCat Sample Events ✅ Step-by-Step Guide to Integration 1. Create the Route // routes/ap...

Laravel Relationships Explained – A Beginner-Friendly Guide

Laravel Relationships Explained – Eloquent ORM Guide Laravel's Eloquent ORM provides a beautiful, simple implementation for working with your database. One of its most powerful features is the ability to define relationships between different models. Understanding relationships allows you to link database tables through Eloquent and run complex queries with minimal effort. 📁 What is a Relationship? A relationship in Laravel refers to the connection between two or more Eloquent models (database tables). Relationships allow us to access related data using simple methods instead of writing complex SQL joins. 💼 When Should You Use Relationships? Use relationships when: One model is logically related to another (e.g., a User has a Profile) You want to avoid writing raw SQL JOIN queries You want to access related records easily using model methods 1. hasOne The hasOne relationship defines a one...

How Can We Optimize a Laravel Project?

How Can We Optimize a Laravel Project? If you're building a web application using Laravel, performance becomes very important as your app grows. In this guide, we'll break down the most effective and beginner-friendly ways to optimize your Laravel project — from caching and database tips to using Laravel Octane and monitoring tools. 🚀 1. Use Caching Wherever Possible What is caching? Caching means temporarily storing data to reduce the time it takes to access it again. Laravel supports caching routes, views, config, and even database queries. How it helps: Instead of performing the same task every time (like querying the database), Laravel uses cached results, making your app much faster. Route Cache: Speeds up route loading – php artisan route:cache Config Cache: Combines all your config files for faster loading – php artisan config:cache View Cache: Pre-compiles Blade views – php artisan view:cache Query Cache: St...

Laravel Blade Templating – Tips & Tricks

Laravel Blade Templating – Tips & Tricks Laravel Blade is a powerful templating engine that makes frontend development smooth, elegant, and productive. Whether you're a beginner or experienced developer, these tips will help you write cleaner, reusable, and more efficient Blade templates. 🔁 1. Loop Enhancements Use Blade's built-in $loop variable to get index, first, last, even, etc. @foreach ($users as $user) <p>{{ $loop->index }} - {{ $user->name }}</p> @if ($loop->first) <span>This is the first user</span> @endif @if ($loop->last) <span>This is the last user</span> @endif @endforeach ⚙️ 2. Blade Components Create reusable UI blocks using components: php artisan make:component Alert Then in your view: <x-alert type="success" message="User saved successfully!" /> 📦 3. Blade Slots Use slots to inject content into Blade compon...

Conditional Migration in Laravel 11 Using shouldRun() – Step-by-Step Guide

Conditional Migration in Laravel 11 Using shouldRun() Laravel 11 introduces a powerful feature: the shouldRun() method in migration classes. It allows you to conditionally execute a migration based on custom logic. This is especially useful when: ✅ You want to avoid duplicate column additions. ✅ Your migration depends on the presence of another table. ✅ You want to ensure foreign keys or indexes don’t already exist. 🛠️ Step 1: Install Laravel 11 composer create-project "laravel/laravel:^11.0" conditional-migration 🗄️ Step 2: Configure Database DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_database_name DB_USERNAME=your_username DB_PASSWORD=your_password 📦 Step 3: Run Default Migrations php artisan migrate ✏️ Step 4: Create a New Migration php artisan make:migration add_profile_completed_to_users_table Edit the migration file to use shouldRun() : public function shoul...