Install Paratest and run Laravel tests in parallel
Source: https://laravel.com/docs/12.x/testing
This command installs the brianium/paratest Composer package as a development dependency, which is required for parallel test execution. Subsequently, php artisan test --parallel runs the test suite across multiple processes, significantly reducing execution time.
composer require brianium/paratest --dev
php artisan test --parallel
Define basic Laravel test cases for Pest and PHPUnit
Source: https://laravel.com/docs/12.x/testing
These examples illustrate the syntax for defining simple test cases in Laravel, using both Pest and PHPUnit. They show how to structure a basic test function or method, including assertions, to verify expected behavior.
<?php
test('basic', function () {
expect(true)->toBeTrue();
});
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_basic_test(): void
{
$this->assertTrue(true);
}
}
Report test coverage for Laravel application
Source: https://laravel.com/docs/12.x/testing
This command runs the Laravel test suite and generates a test coverage report, provided Xdebug or PCOV is installed. The report indicates which parts of the application code are exercised by the tests, helping developers identify untested areas.
php artisan test --coverage
Create Eloquent Model Record after $fillable Setup in PHP
Source: https://laravel.com/docs/12.x/eloquent
After defining the mass assignable attributes using $fillable, this snippet shows how to use the create method to insert a new record into the database. The method returns the newly created model instance.
$flight = Flight::create(['name' => 'London to Paris']);
Start Laravel Development Server and Build Assets
Source: https://laravel.com/docs/12.x/installation
Navigate into your newly created Laravel application directory. These commands install Node.js dependencies, build frontend assets, and then launch Laravel’s local development server, queue worker, and Vite development server concurrently using the dev Composer script.
cd example-app
npm install && npm run build
composer run dev
Define parallel testing hooks in Laravel using ParallelTesting facade
Source: https://laravel.com/docs/12.x/testing
This PHP code snippet demonstrates how to define setUp and tearDown hooks for parallel test processes and test cases within a Laravel Service Provider. It uses the ParallelTesting facade to execute custom logic before or after test processes and cases, such as seeding databases for each process, ensuring resources are properly managed for isolated test runs.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\ParallelTesting;
use Illuminate\Support\ServiceProvider;
use PHPUnit\Framework\TestCase;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
ParallelTesting::setUpProcess(function (int $token) {
// ...
});
ParallelTesting::setUpTestCase(function (int $token, TestCase $testCase) {
// ...
});
// Executed when a test database is created...
ParallelTesting::setUpTestDatabase(function (string $database, int $token) {
Artisan::call('db:seed');
});
ParallelTesting::tearDownTestCase(function (int $token, TestCase $testCase) {
// ...
});
ParallelTesting::tearDownProcess(function (int $token) {
// ...
});
}
}
Configure Travis CI for Laravel Dusk Tests
Source: https://laravel.com/docs/12.x/dusk
This YAML configuration for .travis.yml sets up a PHP environment for Laravel Dusk tests on Travis CI. It includes installing Chrome, running composer install, generating an app key, starting google-chrome-stable in headless mode, and running php artisan serve and php artisan dusk.
language: php
php:
- 8.2
addons:
chrome: stable
install:
- cp .env.testing .env
- travis_retry composer install --no-interaction --prefer-dist
- php artisan key:generate
- php artisan dusk:chrome-driver
before_script:
- google-chrome-stable --headless --disable-gpu --remote-debugging-port=9222 http://localhost &
- php artisan serve --no-reload &
script:
- php artisan dusk
Install Laravel Reverb Broadcasting Tools
Source: https://laravel.com/docs/12.x/reverb
This Artisan command installs Laravel Reverb along with sensible default configurations for real-time WebSocket communication within a Laravel application. It automates the setup process, running the underlying reverb:install command.
php artisan install:broadcasting
Configure GitHub Actions Workflow for Laravel Dusk Tests
Source: https://laravel.com/docs/12.x/dusk
This YAML workflow defines steps for running Laravel Dusk tests on GitHub Actions. It includes checking out code, preparing the environment, setting up a MySQL database, installing dependencies, generating an app key, starting ChromeDriver, running php artisan serve, executing Dusk tests, and uploading screenshots/console logs on failure.
name: CI
on: [push]
jobs:
dusk-php:
runs-on: ubuntu-latest
env:
APP_URL: 'http://127.0.0.1:8000'
DB_USERNAME: root
DB_PASSWORD: root
MAIL_MAILER: log
steps:
- uses: actions/checkout@v5
- name: Prepare The Environment
run: cp .env.example .env
- name: Create Database
run: |
sudo systemctl start mysql
mysql --user="root" --password="root" -e "CREATE DATABASE \`my-database\` character set UTF8mb4 collate utf8mb4_bin;"
- name: Install Composer Dependencies
run: composer install --no-progress --prefer-dist --optimize-autoloader
- name: Generate Application Key
run: php artisan key:generate
- name: Upgrade Chrome Driver
run: php artisan dusk:chrome-driver --detect
- name: Start Chrome Driver
run: ./vendor/laravel/dusk/bin/chromedriver-linux --port=9515 &
- name: Run Laravel Server
run: php artisan serve --no-reload &
- name: Run Dusk Tests
run: php artisan dusk
- name: Upload Screenshots
if: failure()
uses: actions/upload-artifact@v4
with:
name: screenshots
path: tests/Browser/screenshots
- name: Upload Console Logs
if: failure()
uses: actions/upload-artifact@v4
with:
name: console
path: tests/Browser/console
Build Constrained Queries with Laravel Eloquent Models
Source: https://laravel.com/docs/12.x/eloquent
This example illustrates how to construct more specific queries by adding constraints to an Eloquent model. Since Eloquent models act as query builders, methods like where(), orderBy(), and limit() can be chained before calling get() to retrieve a filtered set of results.
$flights = Flight::where('active', 1)
->orderBy('name')
->limit(10)
->get();
Run Laravel Artisan tests with specific options
Source: https://laravel.com/docs/12.x/testing
This command demonstrates how to run a subset of tests or apply specific behaviors using the Artisan test runner. It allows filtering tests by suite and stopping execution upon the first failure, which is useful for focused debugging.
php artisan test --testsuite=Feature --stop-on-failure
Run Laravel tests from the command line
Source: https://laravel.com/docs/12.x/testing
These commands execute your application’s tests using either Pest, PHPUnit, or the Laravel Artisan test runner. Running tests is crucial for verifying application functionality and catching regressions during development.
./vendor/bin/pest
./vendor/bin/phpunit
php artisan test
Add Homestead Domain to Local Hosts File
Source: https://laravel.com/docs/12.x/homestead
This text snippet shows an example entry for your local machine’s hosts file (/etc/hosts on Linux/macOS, C:\Windows\System32\drivers\etc\hosts on Windows). It directs traffic for homestead.test to the Homestead VM’s IP address, enabling local access to your Homestead sites.
192.168.56.56 homestead.test
Replicate Laravel Eloquent Model Instance
Source: https://laravel.com/docs/12.x/eloquent
Demonstrates how to create an unsaved copy of an existing Eloquent model instance using the replicate method. It shows creating a shipping address and then replicating it to create a billing address with updated attributes.
use App\Models\Address;
$shipping = Address::create([
'type' => 'shipping',
'line_1' => '123 Example Street',
'city' => 'Victorville',
'state' => 'CA',
'postcode' => '90001',
]);
$billing = $shipping->replicate()->fill([
'type' => 'billing'
]);
$billing->save();
Retrieve Blade Component Attributes Starting with a Prefix
Source: https://laravel.com/docs/12.x/blade
This example shows how to use the whereStartsWith method to get all attributes whose keys begin with a specified string. It’s a convenient way to select attributes based on naming conventions, like wire:model.
{{ $attributes->whereStartsWith('wire:model') }}
Create a New Laravel Application
Source: https://laravel.com/docs/12.x/installation
After installing the Laravel installer, this command creates a new Laravel project with the specified name (e.g., ‘example-app’). It prompts you to select your preferred testing framework, database, and starter kit during the creation process.
laravel new example-app
Profile slow Laravel tests
Source: https://laravel.com/docs/12.x/testing
This command executes the Laravel test suite and profiles the execution time of individual tests. It then lists the ten slowest tests, allowing developers to identify and optimize performance bottlenecks in their test suite.
php artisan test --profile
Run Laravel tests in parallel with a specific number of processes
Source: https://laravel.com/docs/12.x/testing
This command executes the Laravel test suite in parallel, explicitly specifying the number of concurrent processes to use. It allows fine-tuning resource utilization for test execution, overriding the default behavior of using all available CPU cores.
php artisan test --parallel --processes=4
Create Stripe Setup Intent in Laravel
Source: https://laravel.com/docs/12.x/billing
Utilize Laravel Cashier’s createSetupIntent method to generate a Stripe Setup Intent. This method, called from a route or controller, prepares the backend for securely gathering customer payment details for future subscription use and passes the intent to a view.
return view('update-payment-method', [
'intent' => $user->createSetupIntent()
]);
Configure Advanced Shared Folder Options with rsync in Homestead.yaml (YAML)
Source: https://laravel.com/docs/12.x/homestead
Utilize advanced options for Vagrant’s Synced Folders by specifying them under the options key in Homestead.yaml. This example demonstrates configuring rsync with verbose output, archive mode, deletion, compression, and exclusion of node_modules.
folders:
- map: ~/code/project1
to: /home/vagrant/project1
type: 'rsync'
options:
rsync__args: ['--verbose', '--archive', '--delete', '-zz']
rsync__exclude: ['node_modules']
Install Laravel Homestead Per Project via Composer
Source: https://laravel.com/docs/12.x/homestead
This shell command uses Composer to install Laravel Homestead as a development dependency for a specific project. This allows for project-specific Homestead configurations and inclusion of the Vagrantfile within the project’s repository.
composer require laravel/homestead --dev
Clone Homestead Repository from GitHub (Shell)
Source: https://laravel.com/docs/12.x/homestead
This command clones the Laravel Homestead repository from GitHub into a ‘Homestead’ folder within your user’s home directory. This is the foundational step for setting up your Homestead development environment.
git clone https://github.com/laravel/homestead.git ~/Homestead
Destroy Homestead Virtual Machine
Source: https://laravel.com/docs/12.x/homestead
Before updating Homestead, it’s recommended to destroy your current virtual machine. This command removes the existing VM, preparing the environment for a fresh setup or an update to a new Vagrant box version.
vagrant destroy
Example Laravel Eloquent Observer Class Structure
Source: https://laravel.com/docs/12.x/eloquent
This PHP code defines a standard Laravel Eloquent observer class. It includes methods for handling various model lifecycle events such as created, updated, deleted, restored, and forceDeleted, each receiving the affected model instance.
<?php
namespace AppObservers;
use AppModelsUser;
class UserObserver
{
/**
* Handle the User "created" event.
*/
public function created(User $user): void
{
// ...
}
/**
* Handle the User "updated" event.
*/
public function updated(User $user): void
{
// ...
}
/**
* Handle the User "deleted" event.
*/
public function deleted(User $user): void
{
// ...
}
/**
* Handle the User "restored" event.
*/
public function restored(User $user): void
{
// ...
}
/**
* Handle the User "forceDeleted" event.
*/
public function forceDeleted(User $user): void
{
// ...
}
}
Generate Homestead Configuration Files for Project
Source: https://laravel.com/docs/12.x/homestead
These shell commands invoke Homestead’s make command to generate the Vagrantfile and Homestead.yaml files within the root of a project. This sets up the necessary configuration for a per-project Homestead installation, automatically configuring sites and folders.
# macOS / Linux...
php vendor/bin/homestead make
# Windows...
vendor\bin\homestead make
View SQL Query with Laravel Global Scope Applied
Source: https://laravel.com/docs/12.x/eloquent
Illustrates the resulting SQL query when a global scope is applied to an Eloquent model. It shows how the created_at constraint from the AncientScope is incorporated into the SELECT statement.
select * from `users` where `created_at` < 0021-02-18 00:00:00
Add Query Parameters to GET Requests in Laravel PHP
Source: https://laravel.com/docs/12.x/http-client
Demonstrates how to add query parameters to GET requests in Laravel’s HTTP client. The first example shows direct inclusion or via an array in the get method, while the second demonstrates using withQueryParameters with retry for more complex setups.
$response = Http::get('http://example.com/users', [
'name' => 'Taylor',
'page' => 1,
]);
Http::retry(3, 100)->withQueryParameters([
'name' => 'Taylor',
'page' => 1,
])->get('http://example.com/users');
Retrieve Coupon from Laravel Cashier Promotion Code Object
Source: https://laravel.com/docs/12.x/billing
This PHP example shows how to access the underlying Laravel\Cashier\Coupon object from a PromotionCode instance. After finding a promotion code, the coupon() method is invoked to get details about the associated discount.
$coupon = $user->findPromotionCode('SUMMERSALE')->coupon();
Create New Laravel Application with a Community Starter Kit
Source: https://laravel.com/docs/12.x/starter-kits
Use the Laravel installer’s --using flag to create a new application based on a community-maintained starter kit available on Packagist. Replace example/starter-kit with the desired package name.
laravel new my-app --using=example/starter-kit
Group conditions for chunkById queries in PHP
Source: https://laravel.com/docs/12.x/eloquent
This example demonstrates how to logically group complex where conditions within a closure when using chunkById. This is necessary because chunkById adds its own where conditions for ID filtering, and grouping ensures custom conditions are correctly applied.
Flight::where(function ($query) {
$query->where('delayed', true)->orWhere('cancelled', true);
})->chunkById(200, function (Collection $flights) {
$flights->each->update([
'departed' => false,
'cancelled' => true
]);
}, column: 'id');
Start Laravel Development Server with Inertia SSR
Source: https://laravel.com/docs/12.x/starter-kits
Conveniently start both the Laravel development server and the Inertia SSR server simultaneously. This command first builds an SSR compatible bundle, then launches the servers for local testing of server-side rendered Inertia applications.
composer dev:ssr
Update Homestead Dependency via Composer
Source: https://laravel.com/docs/12.x/homestead
If Homestead is installed as a project dependency via composer.json, this command updates the laravel/homestead package. Ensure your composer.json file contains the correct version constraint, such as "laravel/homestead": "^12", to get the desired updates.
composer update
Build and Start Vite SSR Server
Source: https://laravel.com/docs/12.x/vite
After configuring your package.json for SSR, run npm run build to compile your assets, including the SSR entry point. Then, start the SSR server by executing the compiled Node.js SSR bundle, which will handle server-side rendering requests.
npm run build
node bootstrap/ssr/ssr.js
Recreate parallel test databases in Laravel
Source: https://laravel.com/docs/12.x/testing
This command runs Laravel tests in parallel and forces the recreation of test databases for each parallel process. It ensures a clean database state for every test run, preventing data conflicts or inconsistencies from previous test invocations.
php artisan test --parallel --recreate-databases
Retrieve Original Eloquent Model Attributes with getOriginal (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This example demonstrates the getOriginal method, which returns the attribute values as they were when the model was first retrieved from the database, regardless of subsequent changes. It can retrieve the original value of a specific attribute or all original attributes.
$user = User::find(1);
$user->name; // John
$user->email; // john@example.com
$user->name = 'Jack';
$user->name; // Jack
$user->getOriginal('name'); // John
$user->getOriginal(); // Array of original attributes...
Define Laravel Eloquent Global Scope Class
Source: https://laravel.com/docs/12.x/eloquent
Provides an example of writing a global scope by implementing the Illuminate\Database\Eloquent\Scope interface. The apply method is used to add where constraints or other clauses to the Eloquent query builder, ensuring consistent query behavior across a model.
<?php
namespace App\Models\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class AncientScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*/
public function apply(Builder $builder, Model $model): void
{
$builder->where('created_at', '<', now()->subYears(2000));
}
}
Confirm Card Setup with Stripe.js
Source: https://laravel.com/docs/12.x/billing
Implement the confirmCardSetup method from Stripe.js to finalize the payment method setup process. This JavaScript code listens for a button click, uses the client secret to confirm the card with Stripe, and then handles the success or error response, providing feedback to the user.
const cardHolderName = document.getElementById('card-holder-name');
const cardButton = document.getElementById('card-button');
const clientSecret = cardButton.dataset.secret;
cardButton.addEventListener('click', async (e) => {
const { setupIntent, error } = await stripe.confirmCardSetup(clientSecret, {
payment_method: {
card: cardElement,
billing_details: { name: cardHolderName.value },
},
});
if (error) {
// Display "error.message" to the user...
} else {
// The card has been verified successfully...
}
});
Checkout Homestead Release Branch (Shell)
Source: https://laravel.com/docs/12.x/homestead
After cloning, navigate into the Homestead directory and switch to the ‘release’ branch. This ensures you are using the latest stable version of Homestead, preventing potential compatibility issues.
cd ~/Homestead
git checkout release
Initialize Homestead Configuration File (Shell/Batch)
Source: https://laravel.com/docs/12.x/homestead
Execute the init.sh (macOS/Linux) or init.bat (Windows) command from the Homestead directory. This script generates the Homestead.yaml configuration file, which is central to customizing your Homestead environment.
# macOS / Linux...
bash init.sh
# Windows...
init.bat
Update Laravel Installer using Composer Global
Source: https://laravel.com/docs/12.x/upgrade
This command updates the global Laravel installer package via Composer, ensuring compatibility with Laravel 12.x and new starter kits. Run this if you installed the installer globally using Composer.
composer global update laravel/installer
Enable Blackfire Profiling in Homestead (YAML)
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration snippet integrates Blackfire profiling into your Homestead environment by adding it to the features section of Homestead.yaml. You must provide valid server_id, server_token, client_id, and client_token obtained from your Blackfire account. This setup allows you to profile web requests and CLI applications for performance analysis.
features:
- blackfire:
server_id: 'server_id'
server_token: 'server_value'
client_id: 'client_id'
client_token: 'client_value'
Update or Create Eloquent Model using updateOrCreate (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This example illustrates the updateOrCreate method, which updates an existing model if matching criteria are found, or creates a new one. The first array specifies the search criteria, and the second array provides attributes to update or create with. This method persists the model without needing a separate save call.
$flight = Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99, 'discounted' => 1]
);
Retrieve Single Eloquent Model with Fallback Closure (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This PHP example demonstrates the findOr and firstOr methods, which attempt to retrieve a single Eloquent model. If no model is found, a provided closure is executed, and its return value becomes the result. This is useful for defining default behavior or custom actions when a record is not found.
$flight = Flight::findOr(1, function () {
// ...
});
$flight = Flight::where('legs', '>', 3)->firstOr(function () {
// ...
});
Configure Xdebug Autostart for Web Requests (INI)
Source: https://laravel.com/docs/12.x/homestead
This configuration snippet for 20-xdebug.ini within your Homestead VM forces Xdebug to start automatically for incoming web requests. It sets the client_host, mode to debug, and start_with_request to yes. This is particularly useful for debugging functional tests without needing to pass specific headers or cookies.
; If Homestead.yaml contains a different subnet for the IP address, this address may be different...
xdebug.client_host = 192.168.10.1
xdebug.mode = debug
xdebug.start_with_request = yes
Build Inertia Server-Side Rendering Bundle
Source: https://laravel.com/docs/12.x/starter-kits
For React and Vue starter kits compatible with Inertia SSR, run this command to build an SSR compatible bundle. This prepares your application for server-side rendering capabilities.
npm run build:ssr
Iterate over Eloquent Collection in PHP
Source: https://laravel.com/docs/12.x/eloquent
This example shows how to loop through an Eloquent Collection using a foreach construct. Since Laravel collections implement PHP’s iterable interfaces, they can be treated like arrays for iteration, allowing direct access to model properties.
foreach ($flights as $flight) {
echo $flight->name;
}
Execute Eloquent Operations Without Updating Timestamps in Laravel
Source: https://laravel.com/docs/12.x/eloquent
This PHP example demonstrates how to perform operations on an Eloquent model without triggering an update to its updated_at timestamp. By wrapping the operation within the Model::withoutTimestamps closure, the timestamp remains unchanged.
Model::withoutTimestamps(fn () => $post->increment('reads'));
Define Dynamic Eloquent Scopes with Parameters in Laravel Models
Source: https://laravel.com/docs/12.x/eloquent
This example shows how to define a dynamic scope that accepts parameters, allowing for flexible filtering based on runtime values. Parameters are added to the scope method’s signature after the $query parameter, making scopes highly adaptable.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Scope a query to only include users of a given type.
*/
#[Scope]
protected function ofType(Builder $query, string $type): void
{
$query->where('type', $type);
}
}
Create New Laravel Cashier Subscription with Multiple Products and Quantities
Source: https://laravel.com/docs/12.x/billing
This example extends creating a multi-product subscription by demonstrating how to specify a quantity for a particular price (e.g., 5 for ‘price_chat’) using the quantity method when initializing the new subscription. This allows for fine-grained control over each product’s billing.
$user = User::find(1);
$user->newSubscription('default', ['price_monthly', 'price_chat'])
->quantity(5, 'price_chat')
->create($paymentMethod);
Configure Laravel Eloquent to Prevent Lazy Loading
Source: https://laravel.com/docs/12.x/eloquent
This example demonstrates how to configure Eloquent to prevent lazy loading of relationships using the Model::preventLazyLoading() method. It’s often conditionally applied, such as only in non-production environments, and should typically be invoked in the boot method of an AppServiceProvider.
use Illuminate\Database\Eloquent\Model;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Model::preventLazyLoading(! $this->app->isProduction());
}
Configure Laravel Echo instance for frontend applications
Source: https://laravel.com/docs/12.x/broadcasting
Initializes a new Laravel Echo instance in the frontend application, configuring it to use Pusher as the broadcaster with environment variables for key, cluster, and TLS. Separate examples are provided for plain JavaScript, React, and Vue.
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: import.meta.env.VITE_PUSHER_APP_KEY,
cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
forceTLS: true,
});
import { configureEcho } from '@laravel/echo-react';
configureEcho({
broadcaster: 'pusher',
// key: import.meta.env.VITE_PUSHER_APP_KEY,
// cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
// forceTLS: true,
// wsHost: import.meta.env.VITE_PUSHER_HOST,
// wsPort: import.meta.env.VITE_PUSHER_PORT,
// wssPort: import.meta.env.VITE_PUSHER_PORT,
// enabledTransports: ["ws", "wss"],
});
import { configureEcho } from '@laravel/echo-vue';
configureEcho({
broadcaster: 'pusher',
// key: import.meta.env.VITE_PUSHER_APP_KEY,
// cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
// forceTLS: true,
// wsHost: import.meta.env.VITE_PUSHER_HOST,
// wsPort: import.meta.env.VITE_PUSHER_PORT,
// wssPort: import.meta.env.VITE_PUSHER_PORT,
// enabledTransports: ["ws", "wss"],
});
Start Supervisor Processes on Linux
Source: https://laravel.com/docs/12.x/queues
These shell commands are used to update Supervisor’s configuration and start the defined processes after creating or modifying a configuration file. ‘reread’ scans for new configurations, ‘update’ applies changes, and ‘start’ initiates the specified program.
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start "laravel-worker:*"
Inspect Laravel Eloquent model attributes and relationships
Source: https://laravel.com/docs/12.x/eloquent
The model:show Artisan command provides a comprehensive overview of a specific Eloquent model, detailing its attributes, relationships, and other configured properties directly from the command line. This utility helps developers understand complex models quickly without diving into code.
php artisan model:show Flight
Specify Custom Primary Key in Laravel Eloquent Model
Source: https://laravel.com/docs/12.x/eloquent
By default, Eloquent assumes a primary key column named ‘id’. This example illustrates how to specify a different primary key column name for your model by setting the protected ‘$primaryKey’ property.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'flight_id';
}
Generate Laravel Eloquent model with migration
Source: https://laravel.com/docs/12.x/eloquent
This Artisan command creates a new Eloquent model named Flight and simultaneously generates a corresponding database migration file. This simplifies the process of setting up both the model and its associated database table, promoting consistency.
php artisan make:model Flight --migration
Start Development Servers with Composer
Source: https://laravel.com/docs/12.x/vite
This shell command initiates both the Laravel and Vite development servers. It’s essential for local development when using Vite to compile and serve assets, ensuring all necessary services are running.
composer run dev
Re-hydrate Eloquent Model with refresh() Method
Source: https://laravel.com/docs/12.x/eloquent
This example shows how the refresh() method re-hydrates an existing model instance with the latest data from the database. It updates the current object’s attributes and also refreshes any loaded relationships, effectively reverting any unsaved changes to the model.
$flight = Flight::where('number', 'FR 900')->first();
$flight->number = 'FR 456';
$flight->refresh();
$flight->number; // "FR 900"
Create Eloquent Models with Pending Attributes via Scope in Laravel
Source: https://laravel.com/docs/12.x/eloquent
This example shows how a model created through a scope utilizing withAttributes will automatically inherit those attributes. The draft() scope ensures that any new Post model created through it will have the hidden attribute set to true.
$draft = Post::draft()->create(['title' => 'In Progress']);
$draft->hidden; // true
Configure Homestead Site Type in YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration demonstrates how to specify a site type in Homestead.yaml for applications not based on Laravel, such as Statamic or Symfony. The type directive customizes the Nginx configuration for the specific application framework, optimizing its setup.
sites:
- map: statamic.test
to: /home/vagrant/my-symfony-project/web
type: 'statamic'
Understand React Starter Kit File Structure
Source: https://laravel.com/docs/12.x/starter-kits
This text snippet illustrates the directory structure of the React starter kit’s frontend code, located within resources/js. It outlines the organization of components, hooks, layouts, utilities, pages, and TypeScript definitions for easy modification and customization.
resources/js/
├── components/ # Reusable React components
├── hooks/ # React hooks
├── layouts/ # Application layouts
├── lib/ # Utility functions and configuration
├── pages/ # Page components
└── types/ # TypeScript definitions
Install Laravel Installer Globally via Composer
Source: https://laravel.com/docs/12.x/installation
This command uses Composer to install the Laravel installer package globally. Once installed, the laravel command becomes available in your terminal for creating new Laravel projects efficiently.
composer global require laravel/installer
Install packages in Homestead after.sh avoiding config overwrite (shell)
Source: https://laravel.com/docs/12.x/homestead
This shell command installs a package within Homestead’s after.sh script, specifically configured to prevent overwriting existing configuration files. The Dpkg::Options ensure that Homestead’s default settings are preserved during package installation by forcing the use of default configurations or old versions.
sudo apt-get -y \
-o Dpkg::Options::="--force-confdef" \
-o Dpkg::Options::="--force-confold" \
install package-name
Generate Laravel Eloquent Observer with Artisan
Source: https://laravel.com/docs/12.x/eloquent
This Artisan command generates a new Eloquent observer class. It places the observer in the app/Observers directory and optionally associates it with a specific model, pre-populating common event methods.
php artisan make:observer UserObserver --model=User
Run Telescope Installation and Migrations
Source: https://laravel.com/docs/12.x/telescope
After installing the Telescope package, execute these Artisan commands to publish its assets and migrations, then run the migrations to create the necessary database tables for Telescope’s data storage.
php artisan telescope:install
php artisan migrate
Enforce minimum test coverage threshold in Laravel
Source: https://laravel.com/docs/12.x/testing
This command runs Laravel tests and calculates code coverage, failing the test suite if the coverage percentage falls below the specified minimum threshold. It helps maintain code quality by ensuring a baseline level of test coverage.
php artisan test --coverage --min=80.3
Utilize Local Eloquent Scopes in Laravel Queries
Source: https://laravel.com/docs/12.x/eloquent
Once defined, local scopes can be easily applied to an Eloquent model query. This example shows how to chain multiple scopes, like popular() and active(), along with other query builder methods, to build complex and readable queries.
use App\Models\User;
$users = User::popular()->active()->orderBy('created_at')->get();
Configure Chipper CI for Laravel Dusk Tests
Source: https://laravel.com/docs/12.x/dusk
This YAML configuration for .chipperci.yml sets up a Chipper CI pipeline for Laravel Dusk tests. It specifies PHP and Node versions, includes the Dusk service, defines setup steps (env file, composer), asset compilation (npm), and browser test execution, including starting PHP’s built-in server.
# file .chipperci.yml
version: 1
environment:
php: 8.2
node: 16
# Include Chrome in the build environment
services:
- dusk
# Build all commits
on:
push:
branches: .*
pipeline:
- name: Setup
cmd: |
cp -v .env.example .env
composer install --no-interaction --prefer-dist --optimize-autoloader
php artisan key:generate
# Create a dusk env file, ensuring APP_URL uses BUILD_HOST
cp -v .env .env.dusk.ci
sed -i "s@APP_URL=.*@APP_URL=http://$BUILD_HOST:8000@g" .env.dusk.ci
- name: Compile Assets
cmd: |
npm ci --no-audit
npm run build
- name: Browser Tests
cmd: |
php -S [::0]:8000 -t public 2>server.log &
sleep 2
php artisan dusk:chrome-driver $CHROME_DRIVER
php artisan dusk --env=ci
Regenerate Homestead Virtual Machine
Source: https://laravel.com/docs/12.x/homestead
After updating the Vagrant box and Homestead’s configuration files, this command brings up the Homestead virtual machine. It ensures that the VM is provisioned using the latest Vagrant installation and configurations, applying all recent changes.
vagrant up
Publish shadcn/ui Component in React Projects
Source: https://laravel.com/docs/12.x/starter-kits
This command demonstrates how to publish a shadcn/ui component using npx. It specifies adding the ‘switch’ component, which will be automatically created in resources/js/components/ui/switch.tsx for subsequent use within React pages.
npx shadcn@latest add switch
Update Homestead Source Code with Git
Source: https://laravel.com/docs/12.x/homestead
These Git commands are used to pull the latest Homestead source code from its repository. Executing git fetch and git pull origin release ensures your local Homestead installation is up-to-date with the latest features and bug fixes from the ‘release’ branch.
git fetch
git pull origin release
Filter Eloquent Cursor Results Using Lazy Collections (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This PHP example shows how to apply collection methods, specifically filter, to the results of an Eloquent cursor method. The cursor returns a LazyCollection, allowing for efficient, memory-friendly filtering and iteration of large datasets without loading all models into memory simultaneously.
use App\Models\User;
$users = User::cursor()->filter(function (User $user) {
return $user->id > 500;
});
foreach ($users as $user) {
echo $user->id;
}
Generate a basic Laravel Eloquent model
Source: https://laravel.com/docs/12.x/eloquent
This Artisan command creates a new Eloquent model class named Flight in the app/Models directory. It’s the fundamental way to start defining database interactions in Laravel, providing a clean slate for model definition.
php artisan make:model Flight
Livewire Starter Kit Frontend Directory Structure
Source: https://laravel.com/docs/12.x/starter-kits
This snippet illustrates the typical frontend directory structure for a Livewire 3, Tailwind, and Flux UI-based Laravel starter kit. It highlights where reusable components, Livewire pages, and Blade partials are located within the resources/views directory.
resources/views
├── components # Reusable Livewire components
├── flux # Customized Flux components
├── livewire # Livewire pages
├── partials # Reusable Blade partials
├── dashboard.blade.php # Authenticated user dashboard
├── welcome.blade.php # Guest user welcome page
Update Laravel Installer via php.new for various OS
Source: https://laravel.com/docs/12.x/upgrade
These commands install or update the latest PHP and Laravel installer using php.new for different operating systems. This ensures compatibility with Laravel 12.x and is suitable if you initially installed PHP and Laravel via php.new.
/bin/bash -c "$(curl -fsSL https://php.new/install/mac/8.4)"
# Run as administrator...
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://php.new/install/windows/8.4'))
/bin/bash -c "$(curl -fsSL https://php.new/install/linux/8.4)"
Retrieve or Create Eloquent Models using firstOrCreate and firstOrNew
Source: https://laravel.com/docs/12.x/eloquent
The firstOrCreate method attempts to find a record; if not found, it creates and persists a new one with merged attributes. firstOrNew similarly attempts to find a record but returns an unpersisted new model instance if not found, requiring a manual save() call to persist it to the database.
use App\Models\Flight;
// Retrieve flight by name or create it if it doesn't exist...
$flight = Flight::firstOrCreate([
'name' => 'London to Paris'
]);
// Retrieve flight by name or create it with the name, delayed, and arrival_time attributes...
$flight = Flight::firstOrCreate(
['name' => 'London to Paris'],
['delayed' => 1, 'arrival_time' => '11:30']
);
// Retrieve flight by name or instantiate a new Flight instance...
$flight = Flight::firstOrNew([
'name' => 'London to Paris'
]);
// Retrieve flight by name or instantiate with the name, delayed, and arrival_time attributes...
$flight = Flight::firstOrNew(
['name' => 'Tokyo to Sydney'],
['delayed' => 1, 'arrival_time' => '11:30']
);
Compare Eloquent Models with ‘is’ and ‘isNot’ Methods
Source: https://laravel.com/docs/12.x/eloquent
Demonstrates how to use the is and isNot methods to check if two Eloquent model instances represent the same database record. These methods efficiently verify if models share the same primary key, table, and database connection without issuing additional queries.
if ($post->is($anotherPost)) {
// ...
}
if ($post->isNot($anotherPost)) {
// ...
}
Order Eloquent Results by Subquery Condition (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This PHP example illustrates how to order Eloquent query results using a subquery within the orderByDesc method. It sorts destinations based on the arrival time of their last flight, executing a single, efficient database query to achieve complex sorting logic.
return Destination::orderByDesc(
Flight::select('arrived_at')
->whereColumn('destination_id', 'destinations.id')
->orderByDesc('arrived_at')
->limit(1)
)->get();
Start Inertia SSR Server with Artisan Command
Source: https://laravel.com/docs/12.x/vite
If you are using SSR with Inertia.js, you can leverage Laravel’s inertia:start-ssr Artisan command to conveniently start the server-side rendering process. This command simplifies the deployment and management of Inertia SSR, integrating seamlessly with your Laravel application.
php artisan inertia:start-ssr
Understand Vue Starter Kit File Structure
Source: https://laravel.com/docs/12.x/starter-kits
This text snippet illustrates the directory structure of the Vue starter kit’s frontend code, located within resources/js. It outlines the organization of components, composables, layouts, utilities, pages, and TypeScript definitions for easy modification and customization.
resources/js/
├── components/ # Reusable Vue components
├── composables/ # Vue composables / hooks
├── layouts/ # Application layouts
├── lib/ # Utility functions and configuration
├── pages/ # Page components
└── types/ # TypeScript definitions
Access Homestead Site in Web Browser
Source: https://laravel.com/docs/12.x/homestead
This is the typical URL format used to access a site hosted within the Laravel Homestead environment from your local web browser after the hosts file has been configured.
http://homestead.test
Install Laravel Octane with FrankenPHP via Laravel Sail
Source: https://laravel.com/docs/12.x/octane
These commands initiate Laravel Sail, install the Octane package, and specifically install the FrankenPHP server for Octane within your Sail environment. This prepares your Docker setup to run the application with FrankenPHP.
./vendor/bin/sail up
./vendor/bin/sail composer require laravel/octane
./vendor/bin/sail artisan octane:install --server=frankenphp
Display invoice information in Laravel Blade template
Source: https://laravel.com/docs/12.x/billing
Example Blade template code for iterating through a collection of invoices and displaying their date, total, and a download link. This demonstrates how to present invoice data to the user.
<table>
@foreach ($invoices as $invoice)
<tr>
<td>{{ $invoice->date()->toFormattedDateString() }}</td>
<td>{{ $invoice->total() }}</td>
<td><a href="/user/invoice/{{ $invoice->id }}">Download</a></td>
</tr>
@endforeach
</table>
Start Laravel Reverb Server with Custom Host and Port
Source: https://laravel.com/docs/12.x/reverb
Initiates the Laravel Reverb server, allowing specification of a custom host and port via command-line options. This overrides the default 0.0.0.0:8080.
php artisan reverb:start --host=127.0.0.1 --port=9000
Create new Laravel test files using Artisan
Source: https://laravel.com/docs/12.x/testing
These commands generate new test classes within your Laravel application. The default command creates a feature test, while the --unit flag specifies a unit test, placing them in the tests/Feature or tests/Unit directories respectively.
php artisan make:test UserTest
php artisan make:test UserTest --unit
Re-retrieve Eloquent Model with fresh() Method
Source: https://laravel.com/docs/12.x/eloquent
This snippet demonstrates using the fresh() method to re-retrieve a model from the database. It returns a brand new model instance with the latest data, leaving the original model instance unaffected by the refresh.
$flight = Flight::where('number', 'FR 900')->first();
$freshFlight = $flight->fresh();
Activate Laravel Cashier Subscription Immediately
Source: https://laravel.com/docs/12.x/cashier-paddle
This code demonstrates how to immediately end a subscription’s trial period and activate it. The activate() method is called on the subscription instance, effectively starting paid billing.
$user->subscription()->activate();
Install Project Frontend Dependencies with NPM
Source: https://laravel.com/docs/12.x/vite
Execute this command in your Laravel project’s root directory to install all frontend packages specified in package.json. This includes Vite and the official Laravel Vite plugin, along with any other required UI dependencies.
npm install
Configure Heroku CI for Laravel Dusk Tests
Source: https://laravel.com/docs/12.x/dusk
This JSON configuration specifies buildpacks for PHP and Chrome, and defines test setup and execution scripts for running Laravel Dusk tests on Heroku CI. It includes starting chromedriver and php artisan serve in the background.
{
"environments": {
"test": {
"buildpacks": [{ "url": "heroku/php" }, { "url": "https://github.com/heroku/heroku-buildpack-chrome-for-testing" }],
"scripts": {
"test-setup": "cp .env.testing .env",
"test": "nohup bash -c './vendor/laravel/dusk/bin/chromedriver-linux --port=9515 > /dev/null 2>&1 &' && nohup bash -c 'php artisan serve --no-reload > /dev/null 2>&1 &' && php artisan dusk"
}
}
}
}
Customize Eloquent Model Timestamp Storage Format in Laravel
Source: https://laravel.com/docs/12.x/eloquent
This PHP example demonstrates how to change the format in which date attributes are stored in the database and serialized to arrays/JSON. By setting the $dateFormat property on the Eloquent model, you can specify a custom date format, such as Unix timestamp (‘U’).
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The storage format of the model's date columns.
*
* @var string
*/
protected $dateFormat = 'U';
}
Restore Soft-Deleted Related Eloquent Models (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Demonstrates how to restore soft-deleted models through a relationship using the restore method on the relationship query. This allows restoring related models in bulk.
$flight->history()->restore();
Configure Laravel Eloquent Model to Use ULID Primary Keys
Source: https://laravel.com/docs/12.x/eloquent
This PHP example demonstrates how to use ULID primary keys instead of UUIDs or auto-incrementing integers. By utilizing the HasUlids trait, the model will automatically generate lexicographically sortable ULIDs for its primary key, as shown with an ‘Article’ model.
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasUlids;
// ...
}
$article = Article::create(['title' => 'Traveling to Asia']);
$article->id; // "01gd4d3tgrrfqeda94gdbtdk5c"
Remove Multiple or All Global Scopes from Eloquent Query in Laravel
Source: https://laravel.com/docs/12.x/eloquent
These examples show how to remove multiple or all global scopes from an Eloquent query. You can remove all global scopes, a specific subset by providing an array of class names, or all except a designated list of scopes, offering fine-grained control over query constraints.
User::withoutGlobalScopes()->get();
User::withoutGlobalScopes([
FirstScope::class, SecondScope::class
])->get();
User::withoutGlobalScopesExcept([
SecondScope::class,
])->get();
Assert URL path begins with in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the current URL path begins with the given path. This is useful for verifying the start of a URL’s path segment.
$browser->assertPathBeginsWith('/home');
Configure Laravel Echo for Ably in JavaScript, React, and Vue
Source: https://laravel.com/docs/12.x/broadcasting
These code examples demonstrate how to initialize Laravel Echo in different frontend environments to connect to Ably for real-time broadcasting. They show setting the broadcaster, defining the public key, and configuring the WebSocket host and port for the Ably service.
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: import.meta.env.VITE_ABLY_PUBLIC_KEY,
wsHost: 'realtime-pusher.ably.io',
wsPort: 443,
disableStats: true,
encrypted: true,
});
import { configureEcho } from "@laravel/echo-react";
configureEcho({
broadcaster: "ably",
// key: import.meta.env.VITE_ABLY_PUBLIC_KEY,
// wsHost: "realtime-pusher.ably.io",
// wsPort: 443,
// disableStats: true,
// encrypted: true,
});
import { configureEcho } from "@laravel/echo-vue"; configureEcho({ broadcaster: "ably", // key: import.meta.env.VITE_ABLY_PUBLIC_KEY, // wsHost:
"realtime-pusher.ably.io", // wsPort: 443, // disableStats: true, // encrypted: true, });
Listen to multiple events with useEcho hook (JavaScript)
Source: https://laravel.com/docs/12.x/broadcasting
This example shows how to configure the useEcho hook to listen for an array of multiple event names on a single channel. This approach simplifies event handling for components that need to react to several different events originating from the same broadcast source.
useEcho(`orders.${orderId}`, ['OrderShipmentStatusUpdated', 'OrderShipped'], (e) => {
console.log(e.order);
});
Get Changed and Previous Eloquent Model Attributes (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This snippet shows how to use getChanges to retrieve an array of attributes that were modified during the last save operation, and getPrevious to get the original attribute values before those changes were applied. These methods are useful for auditing or logging changes.
$user = User::find(1);
$user->name; // John
$user->email; // john@example.com;
$user->update([
'name' => 'Jack',
'email' => 'jack@example.com',
]);
$user->getChanges();
/*
[
'name' => 'Jack',
'email' => 'jack@example.com',
]
*/
$user->getPrevious();
/*
[
'name' => 'John',
'email' => 'john@example.com',
]
*/
Retrieve All Records from a Laravel Eloquent Model
Source: https://laravel.com/docs/12.x/eloquent
This code demonstrates the simplest way to fetch all records from a model’s associated database table using the static all() method on the Eloquent model. It then iterates through the retrieved Flight models, echoing each flight’s name.
use App\Models\Flight;
foreach (Flight::all() as $flight) {
echo $flight->name;
}
Create Stripe Customer for Billable Model
Source: https://laravel.com/docs/12.x/billing
Illustrates creating a new Stripe customer for a billable model without immediately starting a subscription. The createAsStripeCustomer method can accept an optional array of Stripe API parameters for customer creation.
$stripeCustomer = $user->createAsStripeCustomer();
$stripeCustomer = $user->createAsStripeCustomer($options);
Perform Basic Browser Login Test with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This snippet demonstrates how to write a basic browser test using Laravel Dusk to log into an application. It creates a user, navigates to the login page, types credentials, presses the login button, and asserts the redirection to the home page. Examples are provided for both Pest and PHPUnit testing frameworks, utilizing DatabaseMigrations.
<?php
use AppModelsUser;
use IlluminateFoundationTestingDatabaseMigrations;
use LaravelDuskBrowser;
pest()->use(DatabaseMigrations::class);
test('basic example', function () {
$user = User::factory()->create([
'email' => 'taylor@laravel.com',
]);
$this->browse(function (Browser $browser) use ($user) {
$browser->visit('/login')
->type('email', $user->email)
->type('password', 'password')
->press('Login')
->assertPathIs('/home');
});
});
<?php
namespace TestsBrowser;
use AppModelsUser;
use IlluminateFoundationTestingDatabaseMigrations;
use LaravelDuskBrowser;
use TestsDuskTestCase;
class ExampleTest extends DuskTestCase
{
use DatabaseMigrations;
/**
* A basic browser test example.
*/
public function test_basic_example(): void
{
$user = User::factory()->create([
'email' => 'taylor@laravel.com',
]);
$this->browse(function (Browser $browser) use ($user) {
$browser->visit('/login')
->type('email', $user->email)
->type('password', 'password')
->press('Login')
->assertPathIs('/home');
});
}
}
Publish Fortify Resources with Artisan
Source: https://laravel.com/docs/12.x/fortify
After installing the Fortify package, this Artisan command publishes its essential resources, including the service provider, configuration file, database migrations, and action classes, into your application.
php artisan fortify:install
Publish shadcn-vue Component in Vue Projects
Source: https://laravel.com/docs/12.x/starter-kits
This command demonstrates how to publish a shadcn-vue component using npx. It specifies adding the ‘switch’ component, which will be automatically created in resources/js/components/ui/Switch.vue for subsequent use within Vue pages.
npx shadcn-vue@latest add switch
Manage Plain Cookies in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This PHP example shows how to work with unencrypted cookies in Laravel Dusk tests. The plainCookie method allows you to get the value of a plain cookie by its name or set a new unencrypted value for a cookie, bypassing Laravel’s default encryption.
$browser->plainCookie('name');
$browser->plainCookie('name', 'Taylor');
Example Laravel Project Structure for Vite Assets
Source: https://laravel.com/docs/12.x/vite
This text snippet illustrates a typical Laravel project structure relevant for asset handling with Vite. It shows the placement of assets in both the public directory and resources directories, differentiating how Vite might process them based on their location.
public/
taylor.png
resources/
js/
Pages/
Welcome.vue
images/
abigail.png
Laravel Dusk: Example of a fragile CSS selector
Source: https://laravel.com/docs/12.x/dusk
This example illustrates how traditional CSS selectors can become fragile and break tests due to minor frontend changes. It shows an HTML button and the corresponding PHP Dusk test code using a complex CSS selector.
// HTML...
<button>Login</button>
// Test...
$browser->click('.login-page .container div > button');
Run Concurrent Laravel Processes and Get Results Immediately in PHP
Source: https://laravel.com/docs/12.x/processes
This PHP example utilizes the concurrently method to start a pool of asynchronous processes and immediately wait for all of their results. It showcases how to use PHP’s array destructuring to easily assign the ProcessResult instances of each process to distinct variables, providing a concise way to handle multiple concurrent task outcomes.
[$first, $second, $third] = Process::concurrently(function (Pool $pool) {
$pool->path(__DIR__)->command('ls -la');
$pool->path(app_path())->command('ls -la');
$pool->path(storage_path())->command('ls -la');
});
echo $first->output();
Enable Minio Object Storage in Homestead
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration enables the Minio object storage server feature within Homestead. Adding minio: true to the features section of your Homestead.yaml file installs Minio, which is accessible by default on port 9600.
minio: true
Check Eloquent Model Attribute Changes with isDirty and isClean (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This example demonstrates how to use isDirty and isClean methods to check for attribute changes since the model was retrieved or saved. isDirty returns true if any attributes have changed, and isClean returns true if no attributes have changed. Both methods can accept specific attribute names or arrays of names.
use App\Models\User;
$user = User::create([
'first_name' => 'Taylor',
'last_name' => 'Otwell',
'title' => 'Developer',
]);
$user->title = 'Painter';
$user->isDirty(); // true
$user->isDirty('title'); // true
$user->isDirty('first_name'); // false
$user->isDirty(['first_name', 'title']); // true
$user->isClean(); // false
$user->isClean('title'); // false
$user->isClean('first_name'); // true
$user->isClean(['first_name', 'title']); // false
$user->save();
$user->isDirty(); // false
$user->isClean(); // true
Define a basic Laravel controller with a show method
Source: https://laravel.com/docs/12.x/controllers
This PHP example demonstrates a basic Laravel controller (UserController) with a public show method. It shows how to retrieve data (a User model) and return a view, illustrating dependency injection for View and type-hinting for route parameters.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\View\View;
class UserController extends Controller
{
/**
* Show the profile for a given user.
*/
public function show(string $id): View
{
return view('user.profile', [
'user' => User::findOrFail($id)
]);
}
}
Detect and Install ChromeDriver for Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This Artisan command automatically detects your currently installed Chrome/Chromium browser version and downloads the compatible ChromeDriver executable for your operating system. It’s the recommended way to set up ChromeDriver for Laravel Dusk.
php artisan dusk:chrome-driver --detect
Start Laravel Octane with File Change Watching
Source: https://laravel.com/docs/12.x/octane
This command starts the Laravel Octane server and automatically restarts it when application files change. This feature is crucial for development environments, requiring Node.js and the Chokidar library to be installed.
php artisan octane:start --watch
Register Eloquent Model Events with Closures in ‘booted’ Method
Source: https://laravel.com/docs/12.x/eloquent
Demonstrates how to register model event listeners using closures directly within the booted method of an Eloquent model. This provides a concise way to define event handling logic, such as reacting to a created event, without requiring separate event classes.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The "booted" method of the model.
*/
protected static function booted(): void
{
static::created(function (User $user) {
// ...
});
}
}
Install Laravel Octane and RoadRunner via Laravel Sail
Source: https://laravel.com/docs/12.x/octane
These commands are used within a Laravel Sail environment to set up Octane and RoadRunner. The first command starts Sail, and the second uses Composer to install the necessary Laravel Octane, RoadRunner CLI, and RoadRunner HTTP packages into the project.
./vendor/bin/sail up
./vendor/bin/sail composer require laravel/octane spiral/roadrunner-cli spiral/roadrunner-http
Set Vagrant Provider in Homestead.yaml (YAML)
Source: https://laravel.com/docs/12.x/homestead
Configure the provider key in your Homestead.yaml file to specify whether Homestead should use ‘virtualbox’ or ‘parallels’ as its Vagrant provider. For Apple Silicon users, ‘parallels’ is required.
provider: virtualbox
Show Laravel Database Overview
Source: https://laravel.com/docs/12.x/database
Displays an overview of the default database, including its size, type, number of open connections, and a summary of its tables, using the Artisan db:show command.
php artisan db:show
Register Eloquent Observer with PHP Attribute
Source: https://laravel.com/docs/12.x/eloquent
This PHP code demonstrates how to register an Eloquent observer by applying the ObservedBy attribute directly to the model class. This approach provides a declarative way to link observers to models, simplifying registration.
use AppObserversUserObserver;
use IlluminateDatabaseEloquentAttributesObservedBy;
#[ObservedBy([UserObserver::class])]
class User extends Authenticatable
{
//
}
Configure Livewire Primary Layout
Source: https://laravel.com/docs/12.x/starter-kits
Switch between ‘sidebar’ and ‘header’ primary layouts in your Livewire starter kit. This customization is done by modifying the layout component used in your resources/views/components/layouts/app.blade.php file and adding the container attribute to the main Flux component.
<x-layouts.app.header>
<flux:main container>
{{ $slot }}
</flux:main>
</x-layouts.app.header>
Install Laravel Echo and Pusher JS for Reverb (NPM)
Source: https://laravel.com/docs/12.x/broadcasting
This command installs the laravel-echo and pusher-js packages as development dependencies. pusher-js is required because Reverb uses the Pusher protocol for WebSocket communication, enabling real-time features in your application.
npm install --save-dev laravel-echo pusher-js
Fill Existing Eloquent Model with Attributes in PHP
Source: https://laravel.com/docs/12.x/eloquent
Demonstrates using the fill method on an existing Eloquent model instance to populate its attributes from an array. This method respects the model’s $fillable or $guarded properties for mass assignment protection.
$flight->fill(['name' => 'Amsterdam to Frankfurt']);
Generate Laravel Eloquent model with various associated classes
Source: https://laravel.com/docs/12.x/eloquent
These Artisan commands demonstrate how to generate an Eloquent model along with related classes like factories, seeders, controllers, policies, and form requests. Various options allow for single or multiple class generations simultaneously, streamlining development workflows.
# Generate a model and a FlightFactory class...
php artisan make:model Flight --factory
php artisan make:model Flight -f
# Generate a model and a FlightSeeder class...
php artisan make:model Flight --seed
php artisan make:model Flight -s
# Generate a model and a FlightController class...
php artisan make:model Flight --controller
php artisan make:model Flight -c
# Generate a model, FlightController resource class, and form request classes...
php artisan make:model Flight --controller --resource --requests
php artisan make:model Flight -crR
# Generate a model and a FlightPolicy class...
php artisan make:model Flight --policy
# Generate a model and a migration, factory, seeder, and controller...
php artisan make:model Flight -mfsc
# Shortcut to generate a model, migration, factory, seeder, policy, controller, and form requests...
php artisan make:model Flight --all
php artisan make:model Flight -a
# Generate a pivot model...
php artisan make:model Member --pivot
php artisan make:model Member -p
Example of Vite-Imagetools Outputting Incorrect URLs (HTML)
Source: https://laravel.com/docs/12.x/vite
This HTML snippet illustrates the default URL format generated by the vite-imagetools plugin. It shows a relative URL starting with / which is expected to be handled by the Vite dev server, but in a Laravel context, it might not be.
<img src="/@imagetools/f0b2f404b13f052c604e632f2fb60381bf61a520" />
Listen for Laravel Model Broadcasts with useEchoModel (React, Vue, TS)
Source: https://laravel.com/docs/12.x/broadcasting
This snippet demonstrates how to use the useEchoModel hook in React and Vue to listen for Laravel model broadcasts. It shows how to subscribe to specific model events and includes a TypeScript example for enhanced type safety and better developer experience. Ensure @laravel/echo-react or @laravel/echo-vue is installed.
import { useEchoModel } from '@laravel/echo-react';
useEchoModel('App.Models.User', userId, ['UserUpdated'], (e) => {
console.log(e.model);
});
<script setup lang="ts">
import { useEchoModel } from '@laravel/echo-vue';
useEchoModel('App.Models.User', userId, ['UserUpdated'], (e) => {
console.log(e.model);
});
</script>
type User = {
id: number;
name: string;
email: string;
};
useEchoModel<User, 'App.Models.User'>('App.Models.User', userId, ['UserUpdated'], (e) => {
console.log(e.model.id);
console.log(e.model.name);
});
Enable/Configure Laravel Fortify Two-Factor Authentication
Source: https://laravel.com/docs/12.x/starter-kits
This PHP snippet demonstrates how to enable and configure two-factor authentication (2FA) using Laravel Fortify in your starter kit. It shows how to activate features like ‘confirm’ and ‘confirmPassword’ for enhanced security.
Features::twoFactorAuthentication([
'confirm' => true,
'confirmPassword' => true,
]);
Create Subscription with Multiple Prices in Laravel
Source: https://laravel.com/docs/12.x/cashier-paddle
Demonstrates how to create a new subscription with multiple billing products by passing an array of price IDs to the subscribe method. This example uses a POST route to handle the subscription checkout.
use Illuminate\Http\Request;
Route::post('/user/subscribe', function (Request $request) {
$checkout = $request->user()->subscribe([
'price_monthly',
'price_chat',
]);
return view('billing', ['checkout' => $checkout]);
});
Retrieve Coupon from Laravel Cashier Discount Object
Source: https://laravel.com/docs/12.x/billing
This PHP example demonstrates how to access the Laravel\Cashier\Coupon object associated with a Laravel\Cashier\Discount instance. This allows further inspection of the discount’s details, such as its type and value.
$coupon = $subscription->discount()->coupon();
Stop Listening to Notifications with Laravel Echo in JavaScript
Source: https://laravel.com/docs/12.x/broadcasting
This JavaScript example demonstrates how to stop listening for private channel notifications using Laravel Echo’s stopListeningForNotification method. It first defines a callback function, starts listening to a user-specific notification channel, and then stops listening using the same callback function. Ensure the callback reference is identical when stopping.
const callback = (notification) => {
console.log(notification.type);
};
// Start listening...
Echo.private(`App.Models.User.${userId}`).notification(callback);
// Stop listening (callback must be the same)...
Echo.private(`App.Models.User.${userId}`).stopListeningForNotification(callback);
Convert Generic Trial to Subscription (PHP)
Source: https://laravel.com/docs/12.x/billing
After a generic trial, this code demonstrates how to transition the user to a full subscriber by creating a new subscription using the newSubscription method. A payment method is required at this stage to complete the subscription creation.
$user = User::find(1);
$user->newSubscription('default', 'price_monthly')->create($paymentMethod);
Apply Laravel Eloquent Global Scope Using Attribute
Source: https://laravel.com/docs/12.x/eloquent
Demonstrates how to apply a global scope to an Eloquent model by using the ScopedBy attribute. This modern approach simplifies the registration of global scopes directly on the model class.
<?php
namespace App\Models;
use App\Models\Scopes\AncientScope;
use Illuminate\Database\Eloquent\Attributes\ScopedBy;
#[ScopedBy([AncientScope::class])]
class User extends Model
{
//
}
Configure Laravel Echo with an existing Pusher client
Source: https://laravel.com/docs/12.x/broadcasting
Demonstrates how to configure Laravel Echo to use an already initialized Pusher Channels client instance. This allows for more granular control over the Pusher client setup, passing it directly to Echo’s configuration instead of letting Echo create a new one.
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
const options = {
broadcaster: 'pusher',
key: import.meta.env.VITE_PUSHER_APP_KEY,
};
window.Echo = new Echo({
...options,
client: new Pusher(options.key, options),
});
Install Laravel Fortify via Composer
Source: https://laravel.com/docs/12.x/fortify
This command uses the Composer package manager to download and install the Laravel Fortify package, making it available for use in your Laravel project.
composer require laravel/fortify
Delete All Eloquent Models in a Table (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Demonstrates how to delete all records from a table using an Eloquent query without any conditions. Similar to other mass delete operations, this does not dispatch model events.
$deleted = Flight::query()->delete();
Example Cursor Pagination URL
Source: https://laravel.com/docs/12.x/pagination
This example shows a URL generated by Laravel’s cursor pagination. Unlike offset pagination which uses page numbers, cursor pagination places an encoded ‘cursor’ string in the query string, which indicates the starting point and direction for the next paginated query.
http://localhost/users?cursor=eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0
Initiate Metered Subscription via Stripe Checkout in Laravel
Source: https://laravel.com/docs/12.x/billing
This PHP example shows how to integrate a metered subscription with Stripe Checkout for user-friendly subscription creation. It generates a checkout session and returns it to a view for redirection.
$checkout = Auth::user()
->newSubscription('default', [])
->meteredPrice('price_metered')
->checkout();
return view('your-checkout-view', [
'checkout' => $checkout,
]);
Share Homestead Site via Ngrok (CLI)
Source: https://laravel.com/docs/12.x/homestead
This command makes a specified Homestead site publicly accessible using Ngrok, allowing you to share your local development with others. Replace homestead.test with the actual site name configured in your Homestead.yaml file. The command will display public URLs and an activity log upon execution.
share homestead.test
Check Node.js and NPM Versions
Source: https://laravel.com/docs/12.x/vite
Verify the installed versions of Node.js and npm on your system. This is a prerequisite for running Vite and the Laravel plugin. You can also check versions via Laravel Sail if you are using it for local development.
node -v
npm -v
./vendor/bin/sail node -v
./vendor/bin/sail npm -v
Supervisor Configuration for Laravel Octane Production Deployment
Source: https://laravel.com/docs/12.x/octane
This INI configuration provides a sample Supervisor setup to ensure your Laravel Octane application remains running reliably in a production environment. It defines a program to start artisan octane:start, handles auto-restarts, and logs output, ensuring high availability.
[program:octane]
process_name=%(program_name)s_%(process_num)02d
command=php /home/forge/example.com/artisan octane:start --server=frankenphp --host=127.0.0.1 --port=8000
autostart=true
autorestart=true
user=forge
redirect_stderr=true
stdout_logfile=/home/forge/example.com/storage/logs/octane.log
stopwaitsecs=3600
Handle Not Found Exceptions with Laravel Eloquent findOrFail and firstOrFail
Source: https://laravel.com/docs/12.x/eloquent
These methods retrieve a model based on ID or query conditions, automatically throwing an Illuminate\Database\Eloquent\ModelNotFoundException if no result is found. If uncaught, this exception leads to an automatic 404 HTTP response, streamlining error handling for missing resources.
$flight = Flight::findOrFail(1);
$flight = Flight::where('legs', '>', 3)->firstOrFail();
use App\Models\Flight;
Route::get('/api/flights/{id}', function (string $id) {
return Flight::findOrFail($id);
});
Install Supervisor on Ubuntu
Source: https://laravel.com/docs/12.x/horizon
This command installs the Supervisor process monitor on Ubuntu using apt-get. Supervisor helps manage and restart long-running processes like Laravel Horizon if they stop executing. For other operating systems, use their respective package managers.
sudo apt-get install supervisor
Share Homestead Site with Custom Ngrok Options (CLI)
Source: https://laravel.com/docs/12.x/homestead
This command shares a Homestead site while allowing customization of Ngrok runtime options such as region and subdomain. Use this to create a more controlled or branded public URL for your shared development environment. It’s ideal for specific regional testing or consistent subdomain access.
share homestead.test -region=eu -subdomain=laravel
Run Laravel Database Migrations
Source: https://laravel.com/docs/12.x/installation
This Artisan command executes all pending database migrations, creating or updating the necessary database tables for your Laravel application. This step is crucial after configuring your database or making changes to your migration files.
php artisan migrate
Disable Automatic ChromeDriver Start in Laravel Dusk (PHP)
Source: https://laravel.com/docs/12.x/dusk
To prevent Laravel Dusk from automatically starting ChromeDriver, comment out the static::startChromeDriver() call within the prepare() method of your tests/DuskTestCase.php file. This is necessary if you are manually managing the ChromeDriver process.
/**
* Prepare for Dusk test execution.
*
* @beforeClass
*/
public static function prepare(): void
{
// static::startChromeDriver();
}
Example MySQL Database Connection URL
Source: https://laravel.com/docs/12.x/database
An example of a database connection URL string in the standard format, demonstrating how various connection parameters like username, password, host, database, and options are encapsulated within a single string. Laravel can parse these URLs for database configuration.
mysql://root:password@127.0.0.1/forge?charset=UTF-8
Provide Standard Input to Laravel Process
Source: https://laravel.com/docs/12.x/processes
This code shows how to pass input to the standard input (stdin) of an external process using the input() method. In this example, ‘Hello World’ is piped to the ‘cat’ command, which then outputs it.
$result = Process::input('Hello World')->run('cat');
Start Laravel Reverb Server
Source: https://laravel.com/docs/12.x/reverb
Starts the Laravel Reverb WebSocket server using the Artisan command. By default, it runs on 0.0.0.0:8080.
php artisan reverb:start
Replicate Laravel Eloquent Model Excluding Attributes
Source: https://laravel.com/docs/12.x/eloquent
Illustrates how to replicate an Eloquent model while excluding specific attributes from the new instance. The replicate method accepts an array of attribute names to be excluded during the replication process.
$flight = Flight::create([
'destination' => 'LAX',
'origin' => 'LHR',
'last_flown' => '2020-03-04 11:00:00',
'last_pilot_id' => 747,
]);
$flight = $flight->replicate([
'last_flown',
'last_pilot_id'
]);
Perform Basic HTTP Request and Assert Status (Pest/PHPUnit)
Source: https://laravel.com/docs/12.x/http-tests
This example illustrates how to make a basic HTTP GET request within a Laravel test and assert the response’s HTTP status code. It uses the get() method to simulate a request to the root path and assertStatus(200) to confirm a successful response, returning an Illuminate\Testing\TestResponse instance.
<?php
test('basic request', function () {
$response = $this->get('/');
$response->assertStatus(200);
});
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_a_basic_request(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
Schedule Model Pruning Artisan Command in Laravel
Source: https://laravel.com/docs/12.x/eloquent
This code demonstrates how to schedule the model:prune Artisan command in Laravel’s console kernel. By calling it daily, you can ensure that Prunable models across the application are regularly cleaned up based on their defined pruning logic.
use Illuminate\Support\Facades\Schedule;
Schedule::command('model:prune')->daily();
Run Vite Development and Build Commands
Source: https://laravel.com/docs/12.x/vite
These shell commands are used to interact with Vite. npm run dev starts the Vite development server, enabling Hot Module Replacement (HMR) and automatic file change detection for local development. npm run build compiles and versions your application’s assets, preparing them for production deployment.
# Run the Vite development server...
npm run dev
Register Queueable Closures for Eloquent Model Events
Source: https://laravel.com/docs/12.x/eloquent
Illustrates how to make model event closures queueable using the Illuminate\Events\queueable function. This instructs Laravel to execute the event listener asynchronously in the background via the application’s queue system, improving performance and responsiveness for long-running tasks.
use function Illuminate\Events\queueable;
static::created(queueable(function (User $user) {
// ...
}));
Assert URL hash fragment begins with in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the URL’s current hash fragment begins with the given fragment. This checks the starting part of the URL’s anchor.
$browser->assertFragmentBeginsWith('anchor');
Configure Homestead Sites in YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration block in Homestead.yaml defines multiple Nginx sites for Laravel projects. Each site specifies a map (domain) and a to path (document root) within the Vagrant box. Ensure corresponding folder mappings exist for the project directories.
sites:
- map: homestead.test
to: /home/vagrant/project1/public
- map: another.test
to: /home/vagrant/project2/public
Configure Asset Prefetching to Start on Custom Event
Source: https://laravel.com/docs/12.x/vite
Customize when asset prefetching begins by specifying a custom event that Vite will listen for. This allows for fine-grained control over the prefetching trigger, rather than relying on the default page load event.
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Vite::prefetch(event: 'vite:prefetch');
}
Restore Single Soft-Deleted Eloquent Model (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Shows how to restore a single soft-deleted Eloquent model instance by calling the restore method. This method sets the model’s deleted_at column to null, making it active again.
$flight->restore();
Refactor Podcast Publish Method with Real-Time Facades (PHP)
Source: https://laravel.com/docs/12.x/facades
This code refactors the publish method in the Podcast model to utilize a real-time facade for the Publisher interface. By prefixing Facades\ to the Publisher import, the method no longer needs to explicitly accept a Publisher instance, as it’s resolved automatically from the service container. This maintains testability while simplifying the method signature.
<?php
namespace App\Models;
use Facades\App\Contracts\Publisher; // [tl! add]
use Illuminate\Database\Eloquent\Model;
class Podcast extends Model
{
/**
* Publish the podcast.
*/
public function publish(): void // [tl! add]
{
$this->update(['publishing' => now()]);
Publisher::publish($this); // [tl! add]
}
}
Delete Single Eloquent Model Instance (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Demonstrates how to delete a single Eloquent model instance by calling the delete method on an already retrieved model object. This method dispatches model events.
use App\Models\Flight;
$flight = Flight::find(1);
$flight->delete();
Retrieve all error messages for a field in Laravel
Source: https://laravel.com/docs/12.x/validation
This example shows how to retrieve an array of all error messages for a given field using the get() method on a MessageBag instance. It also includes an example of retrieving messages for array form fields using a wildcard character (‘*’) to access messages for all elements.
foreach ($errors->get('email') as $message) {
// ...
}
foreach ($errors->get('attachments.*') as $message) {
// ...
}
Enable Soft Deletes on Eloquent Model (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Shows how to enable soft deletes for an Eloquent model by adding the Illuminate\Database\Eloquent\SoftDeletes trait to the model class. This ensures that models are not physically deleted but marked with a deleted_at timestamp.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Flight extends Model
{
use SoftDeletes;
}
Install PHP 8.4 on Windows and Linux via php.new
Source: https://laravel.com/docs/12.x/installation
These commands facilitate the installation of PHP 8.4. The Windows command uses PowerShell to bypass execution policy and download an installation script. The Linux command uses curl to download and execute an installation script. A terminal restart is recommended after execution to apply changes.
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://php.new/install/windows/8.4'))
/bin/bash -c "$(curl -fsSL https://php.new/install/linux/8.4)"
Install Flysystem FTP package for Laravel
Source: https://laravel.com/docs/12.x/filesystem
This Composer command installs the league/flysystem-ftp package, which is necessary to enable FTP filesystem support in Laravel. It integrates Flysystem’s FTP capabilities into your application.
composer require league/flysystem-ftp "^3.0"
Initialize Stripe.js and Mount Card Element
Source: https://laravel.com/docs/12.x/billing
Integrate Stripe.js into your frontend to securely capture payment details. This code snippet loads the Stripe library, initializes it with your public key, creates a ‘card’ element, and mounts it into a designated div in your HTML form.
<script src="https://js.stripe.com/v3/"></script>
<script>
const stripe = Stripe('stripe-public-key');
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');
</script>
Define Laravel Console Command with Input and Output
Source: https://laravel.com/docs/12.x/console-tests
This code snippet demonstrates how to define a basic Laravel console command that interacts with the user. It uses ask to get a string, choice for a selection from options, and line to output information to the console. This command serves as an example for subsequent testing scenarios.
Artisan::command('question', function () {
$name = $this->ask('What is your name?');
$language = $this->choice('Which language do you prefer?', [
'PHP',
'Ruby',
'Python',
]);
$this->line('Your name is '.$name.' and you prefer '.$language.'.');
});
Install Laravel Passport via Artisan Command
Source: https://laravel.com/docs/12.x/passport
This Artisan command installs Laravel Passport, publishes and runs necessary database migrations for OAuth2 clients and access tokens, and generates the required encryption keys for secure token generation.
php artisan install:api --passport
Map a Single Shared Folder in Homestead.yaml (YAML)
Source: https://laravel.com/docs/12.x/homestead
Define a single shared folder mapping in the folders property of Homestead.yaml. This synchronizes files between your local machine (e.g., ~/code/project1) and the Homestead virtual environment (/home/vagrant/project1), enabling seamless development.
folders:
- map: ~/code/project1
to: /home/vagrant/project1
Navigate to and Load Laravel Dusk Page Objects
Source: https://laravel.com/docs/12.x/dusk
Demonstrates two methods for interacting with Dusk Page objects in tests. Use visit(new Page) to navigate directly to a page’s URL, or on(new Page) to load a page’s context (selectors and methods) when already on the page without an explicit navigation.
use Tests\Browser\Pages\Login;
$browser->visit(new Login);
use Tests\Browser\Pages\CreatePlaylist;
$browser->visit('/dashboard')
->clickLink('Create Playlist')
->on(new CreatePlaylist)
->assertSee('@create');
Test Real-Time Facades using Pest and PHPUnit (PHP)
Source: https://laravel.com/docs/12.x/facades
These code examples demonstrate how to test the publish method when it utilizes a real-time facade for the Publisher interface. Both Pest and PHPUnit examples show how to mock the real-time facade’s publish method using shouldReceive to assert that it’s called with the correct arguments, ensuring the facade interaction is testable.
<?php
use App\Models\Podcast;
use Facades\App\Contracts\Publisher;
use Illuminate\Foundation\Testing\RefreshDatabase;
pest()->use(RefreshDatabase::class);
test('podcast can be published', function () {
$podcast = Podcast::factory()->create();
Publisher::shouldReceive('publish')->once()->with($podcast);
$podcast->publish();
});
<?php
namespace Tests\Feature;
use App\Models\Podcast;
use Facades\App\Contracts\Publisher;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class PodcastTest extends TestCase
{
use RefreshDatabase;
/**
*
*/
public function test_podcast_can_be_published(): void
{
$podcast = Podcast::factory()->create();
Publisher::shouldReceive('publish')->once()->with($podcast);
$podcast->publish();
}
}
Retrieve Paddle price previews with a discount in PHP
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP example demonstrates fetching price previews while applying a specific discount. By passing a discount_id in the options array to previewPrices, Laravel Cashier calculates and returns the prices after the discount has been applied. This is useful for displaying promotional pricing.
use Laravel\Paddle\Cashier;
$prices = Cashier::previewPrices(['pri_123', 'pri_456'], [
'discount_id' => 'dsc_123'
]);
Start Tailing Laravel Logs with Pail
Source: https://laravel.com/docs/12.x/logging
This command initiates the Laravel Pail utility to start tailing log messages in real time from the command line. Pail effectively works with any log driver configured in Laravel.
php artisan pail
Create User with Generic Trial (PHP)
Source: https://laravel.com/docs/12.x/billing
This code demonstrates how to offer a trial without requiring upfront payment information by setting the trial_ends_at column directly on the user record during creation. This establishes a ‘generic trial’ that is not initially tied to a specific subscription.
use App\Models\User;
$user = User::create([
// ...
'trial_ends_at' => now()->addDays(10),
]);
Start Laravel Reverb Server with Debugging Enabled
Source: https://laravel.com/docs/12.x/reverb
Launches the Laravel Reverb server with the --debug option, enabling the output of detailed stream data for debugging purposes. This helps in monitoring the data flow through the server.
php artisan reverb:start --debug
Specify Product Quantity for Checkout in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This example shows how to perform a product checkout while specifying a custom quantity for the item. The checkout method accepts an associative array where the key is the Price ID and the value is the desired quantity.
use IlluminateHttpRequest;
Route::get('/product-checkout', function (Request $request) {
return $request->user()->checkout(['price_tshirt' => 15]);
});
Configure Optional Homestead Features via YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration block demonstrates how to enable and configure various optional software features within your Homestead.yaml file. Features can be simple booleans or accept detailed configuration, such as specific versions for elasticsearch and authentication details for blackfire.
features:
- blackfire:
server_id: "server_id"
server_token: "server_value"
client_id: "client_id"
client_token: "client_value"
- cassandra: true
- chronograf: true
- couchdb: true
- crystal: true
- dragonflydb: true
- elasticsearch:
version: 7.9.0
- eventstore: true
version: 21.2.0
- flyway: true
- gearman: true
- golang: true
- grafana: true
- influxdb: true
- logstash: true
- mariadb: true
- meilisearch: true
- minio: true
- mongodb: true
- neo4j: true
- ohmyzsh: true
- openresty: true
- pm2: true
- python: true
- r-base: true
- rabbitmq: true
- rustc: true
- rvm: true
- solr: true
- timescaledb: true
- trader: true
- webdriver: true
Check if Eloquent Model is Soft Deleted (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Demonstrates how to check if a model instance has been soft deleted by using the trashed method. This method returns true if the deleted_at timestamp is set.
if ($flight->trashed()) {
// ...
}
Example Laravel SFTP filesystem configuration
Source: https://laravel.com/docs/12.x/filesystem
This PHP array provides an example configuration for an SFTP disk in config/filesystems.php. It supports both basic username/password and SSH key-based authentication, along with settings for file/directory permissions, host fingerprint, and other optional SFTP parameters.
'sftp' => [
'driver' => 'sftp',
'host' => env('SFTP_HOST'),
// Settings for basic authentication...
'username' => env('SFTP_USERNAME'),
'password' => env('SFTP_PASSWORD'),
// Settings for SSH key-based authentication with encryption password...
'privateKey' => env('SFTP_PRIVATE_KEY'),
'passphrase' => env('SFTP_PASSPHRASE'),
// Settings for file / directory permissions...
'visibility' => 'private', // `private` = 0600, `public` = 0644
'directory_visibility' => 'private', // `private` = 0700, `public` = 0755
// Optional SFTP Settings...
// 'hostFingerprint' => env('SFTP_HOST_FINGERPRINT'),
// 'maxTries' => 4,
// 'passphrase' => env('SFTP_PASSPHRASE'),
// 'port' => env('SFTP_PORT', 22),
// 'root' => env('SFTP_ROOT', ''),
// 'timeout' => 30,
// 'useAgent' => true,
],
Connect to Homestead VM via SSH
Source: https://laravel.com/docs/12.x/homestead
This command allows you to establish an SSH connection to your Homestead virtual machine directly from your terminal. Execute it from the directory where your Homestead.yaml file is located to access the VM’s command-line interface.
vagrant ssh
Check User or Subscription Trial Status (PHP)
Source: https://laravel.com/docs/12.x/billing
These examples illustrate how to determine if a user or a specific subscription is currently within a trial period using the onTrial method. Both the user instance and the subscription instance provide this functionality, and they are equivalent in their outcome.
if ($user->onTrial('default')) {
// ...
}
if ($user->subscription('default')->onTrial()) {
// ...
}
Compile Laravel application assets with npm
Source: https://laravel.com/docs/12.x/broadcasting
This shell command initiates the compilation of the application’s frontend assets. Typically, npm run dev uses a build tool like Vite to process JavaScript and CSS, preparing them for deployment or development viewing.
npm run dev
Subscribe Laravel Cashier User After Trial
Source: https://laravel.com/docs/12.x/cashier-paddle
This example illustrates how to initiate a subscription for a user after their trial period, typically through a web route. It uses the subscribe method with a plan ID and returnTo to redirect the user after checkout, then renders a view with the checkout object.
use Illuminate\Http\Request;
Route::get('/user/subscribe', function (Request $request) {
$checkout = $request->user()
->subscribe('pri_monthly')
->returnTo(route('home'));
return view('billing', ['checkout' => $checkout]);
});
Specify Models for Pruning with Laravel Artisan Command
Source: https://laravel.com/docs/12.x/eloquent
This snippet illustrates how to specify particular models to be pruned using the --model option with the model:prune Artisan command. This is useful when models are not in the default app/Models directory or for pruning specific models from a larger application.
Schedule::command('model:prune', [
'--model' => [Address::class, Flight::class],
])->daily();
Get Stripe Customer Object from Billable Model
Source: https://laravel.com/docs/12.x/billing
Retrieves the raw Stripe customer object associated with a billable model. This method assumes the customer already exists in Stripe and returns its representation.
$stripeCustomer = $user->asStripeCustomer();
Configure Laravel Scout to use Database Driver
Source: https://laravel.com/docs/12.x/scout
Sets the SCOUT_DRIVER environment variable or directly in the scout configuration file to database, enabling Laravel Scout to use MySQL or PostgreSQL for full-text search. This driver is the fastest way to get started with Scout.
SCOUT_DRIVER=database
Install Laravel Prompts with Composer (Shell)
Source: https://laravel.com/docs/12.x/prompts
This command installs the Laravel Prompts package into your PHP project using the Composer package manager. It adds the necessary dependency to enable interactive command-line interfaces.
composer require laravel/prompts
Delete Eloquent Models with Query Conditions (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Explains how to perform a mass delete of models that match specific query criteria using the where clause followed by delete(). Note that model events are not dispatched for mass deletes because models are not retrieved individually.
$deleted = Flight::where('active', 0)->delete();
Insert New Eloquent Models using the save Method in Laravel
Source: https://laravel.com/docs/12.x/eloquent
To insert a new record, instantiate an Eloquent model, set its attributes manually, and then call the save() method. The created_at and updated_at timestamps are automatically set upon saving.
<?php
namespace App\Http\Controllers;
use App\Models\Flight;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class FlightController extends Controller
{
/**
* Store a new flight in the database.
*/
public function store(Request $request): RedirectResponse
{
// Validate the request...
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
return redirect('/flights');
}
}
Define Podcast Publish Method with Dependency Injection (PHP)
Source: https://laravel.com/docs/12.x/facades
This code defines a publish method within the Podcast Eloquent model that accepts a Publisher interface instance. It updates the podcast’s publishing timestamp and delegates the actual publishing to the injected Publisher instance. This approach ensures testability but requires explicit dependency passing when calling the method.
<?php
namespace App\Models;
use App\Contracts\Publisher;
use Illuminate\Database\Eloquent\Model;
class Podcast extends Model
{
/**
* Publish the podcast.
*/
public function publish(Publisher $publisher): void
{
$this->update(['publishing' => now()]);
$publisher->publish($this);
}
}
Calculate Conditional Aggregate Values with Laravel avg
Source: https://laravel.com/docs/12.x/queries
This PHP example illustrates combining aggregate methods with where clauses to calculate conditional aggregate values. It shows how to get the average price of only finalized orders.
$price = DB::table('orders')
->where('finalized', 1)
->avg('price');
Set Specific Subscription Quantity in Laravel Cashier Paddle
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP example shows how to set a subscription to a specific quantity value using the updateQuantity method, overriding its current quantity.
$user->subscription()->updateQuantity(10);
Example Laravel FTP filesystem configuration
Source: https://laravel.com/docs/12.x/filesystem
This PHP array demonstrates how to configure an FTP disk in config/filesystems.php. It specifies the driver, host, username, password, and various optional settings like port, root directory, passive mode, SSL, and timeout for connecting to an FTP server.
'ftp' => [
'driver' => 'ftp',
'host' => env('FTP_HOST'),
'username' => env('FTP_USERNAME'),
'password' => env('FTP_PASSWORD'),
// Optional FTP Settings...
// 'port' => env('FTP_PORT', 21),
// 'root' => env('FTP_ROOT'),
// 'passive' => true,
// 'ssl' => true,
// 'timeout' => 30,
],
Apply Laravel Eloquent Global Scope in Model Booted Method
Source: https://laravel.com/docs/12.x/eloquent
Shows how to manually register a global scope by overriding the model’s booted method and calling addGlobalScope. This traditional method allows for programmatic registration of global scopes on a model instance.
<?php
namespace App\Models;
use App\Models\Scopes\AncientScope;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The "booted" method of the model.
*/
protected static function booted(): void
{
static::addGlobalScope(new AncientScope);
}
}
Install Flysystem SFTP package for Laravel
Source: https://laravel.com/docs/12.x/filesystem
This Composer command installs the league/flysystem-sftp-v3 package, which is required to use the SFTP filesystem driver in Laravel. It provides the underlying functionality for secure file transfers using SFTP.
composer require league/flysystem-sftp-v3 "^3.0"
Install Dropbox Flysystem Adapter for Laravel
Source: https://laravel.com/docs/12.x/filesystem
This shell command installs the spatie/flysystem-dropbox package via Composer. This package provides a Flysystem adapter specifically designed for integrating Dropbox as a custom filesystem driver within a Laravel application.
composer require spatie/flysystem-dropbox
Retrieve Single Eloquent Models by Key or Condition (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This PHP snippet showcases various methods to retrieve a single Eloquent model instance. It demonstrates find for primary key lookup, first for the first matching record based on query constraints, and firstWhere as a shorthand for the latter, all returning a single model object.
use App\Models\Flight;
// Retrieve a model by its primary key...
$flight = Flight::find(1);
// Retrieve the first model matching the query constraints...
$flight = Flight::where('active', 1)->first();
// Alternative to retrieving the first model matching the query constraints...
$flight = Flight::firstWhere('active', 1);
Get the sole element from a Laravel Collection with no arguments
Source: https://laravel.com/docs/12.x/collections
This example illustrates calling the sole() method without any arguments to retrieve the single element from a collection. An exception is thrown if the collection contains zero or more than one element.
$collection = collect([
['product' => 'Desk', 'price' => 200],
]);
$collection->sole();
// ['product' => 'Desk', 'price' => 200]
Example of Corrected Vite-Imagetools URLs (HTML)
Source: https://laravel.com/docs/12.x/vite
This HTML snippet shows the resulting URL format after applying the transformOnServe correction in vite.config.js. The devServerUrl is prepended to the /@imagetools path, ensuring the asset points directly to the Vite development server.
- <img src="/@imagetools/f0b2f404b13f052c604e632f2fb60381bf61a520" /><!-- [tl! remove] -->
+ <img src="http://[::1]:5173/@imagetools/f0b2f404b13f052c604e632f2fb60381bf61a520" /><!-- [tl! add] -->
Swap Subscription Plan and Invoice Immediately in Laravel Cashier Paddle
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP example shows how to change a user’s subscription plan and immediately generate an invoice, bypassing the usual next billing cycle, using the swapAndInvoice method.
$user = User::find(1);
$user->subscription()->swapAndInvoice($premium = 'pri_456');
Retrieve Trial Ending Date (PHP)
Source: https://laravel.com/docs/12.x/billing
This example shows how to retrieve the trial ending date for a user, or a specific subscription, using the trialEndsAt method. It returns a Carbon date instance if the user is currently on trial, or null if they are not.
if ($user->onTrial()) {
$trialEndsAt = $user->trialEndsAt('main');
}
Manage Laravel Cashier Subscription Trials
Source: https://laravel.com/docs/12.x/cashier-paddle
Provides code examples for implementing subscription trials where a payment method is collected upfront. This includes defining a route to initiate a trial checkout and various methods to check a user’s trial status, such as checking if they are currently on trial or if their trial has expired, including specific trial types.
use Illuminate\Http\Request;
Route::get('/user/subscribe', function (Request $request) {
$checkout = $request->user()
->subscribe('pri_monthly')
->returnTo(route('home'));
return view('billing', ['checkout' => $checkout]);
});
if ($user->onTrial()) {
// ...
}
if ($user->hasExpiredTrial()) {
// ...
}
if ($user->onTrial('default')) {
// ...
}
if ($user->hasExpiredTrial('default')) {
// ...
}
Force Delete Soft-Deleted Related Eloquent Models (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Shows how to permanently delete soft-deleted related models using the forceDelete method on the relationship query. This is useful for removing associated records that were also soft-deleted.
$flight->history()->forceDelete();
Compile Laravel application frontend assets (NPM)
Source: https://laravel.com/docs/12.x/broadcasting
This command compiles the application’s frontend assets, including JavaScript and CSS. It’s typically run after making changes to frontend code, ensuring that the updated Echo configuration is bundled and ready for deployment.
npm run build
Get a Slice of Laravel Collection using slice()
Source: https://laravel.com/docs/12.x/collections
The slice() method returns a segment of the collection, starting at a specified index and optionally limited by a given size. It creates a new collection, preserving the original keys by default.
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$slice = $collection->slice(4);
$slice->all();
// [5, 6, 7, 8, 9, 10]
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$slice = $collection->slice(4, 2);
$slice->all();
// [5, 6]
View Help Screen for an Artisan Command in Laravel
Source: https://laravel.com/docs/12.x/artisan
Use this command to access the detailed help screen for a specific Artisan command, such as ‘migrate’. It provides information on arguments, options, and usage examples for that command.
php artisan help migrate
Configure Vite Entry Points in vite.config.js
Source: https://laravel.com/docs/12.x/vite
Define the main JavaScript and CSS entry points for your application in the vite.config.js file using the Laravel Vite plugin. This configuration tells Vite which files to process and bundle during development and production builds.
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [laravel(['resources/css/app.css', 'resources/js/app.js'])],
});
Serve Laravel Application with FrankenPHP
Source: https://laravel.com/docs/12.x/deployment
Demonstrates how to quickly serve a Laravel application using the FrankenPHP php-server command, specifying the public/ directory as the document root. This command allows FrankenPHP to act as the web server for the application.
frankenphp php-server -r public/
Laravel Dusk: Retrieving an element’s attribute value
Source: https://laravel.com/docs/12.x/dusk
This example demonstrates how to retrieve the value of a specific attribute from an HTML element. The attribute method requires a selector and the name of the attribute whose value you wish to retrieve.
$attribute = $browser->attribute('selector', 'value');
Basic Laravel Eloquent model class structure
Source: https://laravel.com/docs/12.x/eloquent
This PHP code illustrates the fundamental structure of a Laravel Eloquent model class. Models typically extend Illuminate\Database\Eloquent\Model and reside within the App\Models namespace, forming the basis for object-relational mapping and database interactions.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
// ...
}
Restore Multiple Soft-Deleted Eloquent Models by Query (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Illustrates how to restore multiple soft-deleted models using a query. The withTrashed() method is necessary to include soft-deleted records in the query, followed by restore() for mass restoration. Model events are not dispatched for mass restorations.
Flight::withTrashed()
->where('airline_id', 1)
->restore();
Manually Register Eloquent Observer in Laravel Service Provider
Source: https://laravel.com/docs/12.x/eloquent
This PHP code illustrates how to manually register an Eloquent observer within the boot method of an application’s service provider, typically AppServiceProvider. It uses the observe method on the model to associate an observer class.
use AppModelsUser;
use AppObserversUserObserver;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
User::observe(UserObserver::class);
}
Enable NFS for Shared Folders in Homestead.yaml (YAML)
Source: https://laravel.com/docs/12.x/homestead
Improve shared folder performance and maintain correct user/group permissions by enabling NFS (Network File System). Add the type: "nfs" option to your folder mapping in Homestead.yaml to activate it.
folders:
- map: ~/code/project1
to: /home/vagrant/project1
type: 'nfs'
Start Reverb Server with Custom Hostname for SSL (Herd/Valet)
Source: https://laravel.com/docs/12.x/reverb
Start the Reverb server with specific host, port, and hostname options to utilize local development SSL certificates provided by tools like Laravel Herd or Valet. This enables secure WebSocket connections (wss) for your application during local development, accessible via a secure URL.
php artisan reverb:start --host="0.0.0.0" --port=8080 --hostname="laravel.test"
Compare Related Eloquent Models without Querying
Source: https://laravel.com/docs/12.x/eloquent
Illustrates using the is method on related models accessed through Eloquent relationships like belongsTo or hasOne. This allows comparing a related model instance to another model without executing an additional database query to retrieve it.
if ($post->author()->is($user)) {
// ...
}
Register Multiple Laravel Resource Routes
Source: https://laravel.com/docs/12.x/controllers
This PHP example demonstrates how to register multiple resource controllers simultaneously using the Route::resources method. It accepts an array where keys are the URI prefixes and values are the corresponding controller classes, streamlining the setup for multiple resource types.
Route::resources([
'photos' => PhotoController::class,
'posts' => PostController::class,
]);
Install Laravel Pennant and Publish Assets
Source: https://laravel.com/docs/12.x/pennant
These shell commands are essential for setting up Laravel Pennant. First, Composer installs the package, then Artisan publishes the configuration and migration files, and finally, migrations are run to create the features database table for persistent storage.
composer require laravel/pennant
php artisan vendor:publish --provider="Laravel\Pennant\PennantServiceProvider"
php artisan migrate
Force Delete Single Soft-Deleted Eloquent Model (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Explains how to permanently remove a soft-deleted model from the database using the forceDelete method on the model instance, bypassing the soft delete mechanism. This ensures the record is gone forever.
$flight->forceDelete();
Create Subscription and Send Invoice with Custom Due Days in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP example shows how to create a subscription that sends an invoice, allowing custom specification of the number of days until the invoice is due. The days_until_due option can be passed to the createAndSendInvoice method.
$user->newSubscription('default', 'price_monthly')->createAndSendInvoice([], [
'days_until_due' => 30
]);
Add and Drop Soft Deletes Column in Migration (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Illustrates how to add the deleted_at column to a database table using Laravel’s schema builder for soft deletes. It also shows the helper method to drop the deleted_at column from a table.
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::table('flights', function (Blueprint $table) {
$table->softDeletes();
});
Schema::table('flights', function (Blueprint $table) {
$table->dropSoftDeletes();
});
Install Laravel Telescope for Local-Only Development
Source: https://laravel.com/docs/12.x/telescope
Use these commands to install Laravel Telescope specifically for your local development environment. The --dev flag ensures it’s installed as a development dependency, and subsequent commands set up its assets and database tables.
composer require laravel/telescope --dev
php artisan telescope:install
php artisan migrate
Listen for Laravel Broadcast Events with Laravel Echo
Source: https://laravel.com/docs/12.x/broadcasting
These JavaScript snippets demonstrate how to listen for broadcast events in client-side applications using Laravel Echo. Examples are provided for both React and Vue frameworks, showing how to subscribe to a channel (orders.{orderId}) and process the incoming OrderShipmentStatusUpdated event data.
import { useEcho } from '@laravel/echo-react';
useEcho(`orders.${orderId}`, 'OrderShipmentStatusUpdated', (e) => {
console.log(e.order);
});
<script setup lang="ts">
import { useEcho } from '@laravel/echo-vue';
useEcho(`orders.${orderId}`, 'OrderShipmentStatusUpdated', (e) => {
console.log(e.order);
});
</script>
Get every Nth element from collection (Laravel PHP)
Source: https://laravel.com/docs/12.x/collections
The nth method creates a new collection consisting of every n-th element from the original collection. An optional second argument allows specifying a starting offset for the selection.
$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->nth(4);
// ['a', 'e']
$collection->nth(4, 1);
// ['b', 'f']
Install Laravel Folio service provider
Source: https://laravel.com/docs/12.x/folio
After installing the Folio package, execute this Artisan command to install Folio’s service provider. This command registers the default directory (resources/views/pages) where Folio will search for routes and pages.
php artisan folio:install
Navigate Browser Back and Forward with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
These snippets illustrate how to use the back() and forward() methods to simulate browser navigation history. back() moves to the previous page, and forward() moves to the next page in the history, similar to standard browser navigation buttons.
$browser->back();
$browser->forward();
Retrieve Only Soft Deleted Models in Laravel Eloquent
Source: https://laravel.com/docs/12.x/eloquent
This snippet shows how to query only soft-deleted models using the onlyTrashed method. This is useful for retrieving records that have been marked as deleted but still exist in the database, excluding active models.
$flights = Flight::onlyTrashed()
->where('airline_id', 1)
->get();
Install Flysystem Path Prefixing package for Laravel scoped disks
Source: https://laravel.com/docs/12.x/filesystem
This Composer command installs the league/flysystem-path-prefixing package, which is required to create filesystem disks with path scoping in Laravel. It allows automatically prefixing all paths for operations on a specific disk.
composer require league/flysystem-path-prefixing "^3.0"
Get File Size from Laravel Storage
Source: https://laravel.com/docs/12.x/filesystem
This example demonstrates how to retrieve the size of a file stored via Laravel’s Storage facade. The ‘size’ method returns the file size in bytes, providing essential metadata for file management and display.
use Illuminate\Support\Facades\Storage;
$size = Storage::size('file.jpg');
Force Delete Eloquent Models by Primary Key (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Shows how to permanently delete soft-deleted models using the forceDestroy method by their primary key, bypassing the soft delete mechanism. This is useful for completely removing records from the database.
Flight::forceDestroy(1);
Perform Eloquent Model Operations Without Events
Source: https://laravel.com/docs/12.x/eloquent
This PHP snippet illustrates other ‘quiet’ methods available on Eloquent models, such as deleteQuietly, forceDeleteQuietly, and restoreQuietly. These methods perform their respective operations without dispatching any model events, similar to saveQuietly.
$user->deleteQuietly();
$user->forceDeleteQuietly();
$user->restoreQuietly();
Configure Paddle API and Webhook Keys in .env
Source: https://laravel.com/docs/12.x/cashier-paddle
Set up your Paddle API keys, client-side token, retain key, and webhook secret in your .env file for secure communication with Paddle’s services. Ensure PADDLE_SANDBOX reflects your current environment (true for sandbox, false for production).
PADDLE_CLIENT_SIDE_TOKEN=your-paddle-client-side-token
PADDLE_API_KEY=your-paddle-api-key
PADDLE_RETAIN_KEY=your-paddle-retain-key
PADDLE_WEBHOOK_SECRET="your-paddle-webhook-secret"
PADDLE_SANDBOX=true
Configure Livewire Authentication Page Layout
Source: https://laravel.com/docs/12.x/starter-kits
Change the layout for authentication pages (login, registration) in your Livewire starter kit. This is achieved by updating the layout component within your application’s resources/views/components/layouts/auth.blade.php file to use variants like ‘simple’, ‘card’, or ‘split’.
<x-layouts.auth.split>
{{ $slot }}
</x-layouts.auth.split>
Report Meter Event Usage in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
These PHP snippets demonstrate how to report usage for a metered event to Stripe. The first example reports a default quantity of 1, while the second allows specifying a custom quantity for the usage.
$user = User::find(1);
$user->reportMeterEvent('emails-sent');
$user = User::find(1);
$user->reportMeterEvent('emails-sent', quantity: 15);
Process large Eloquent datasets in chunks using PHP
Source: https://laravel.com/docs/12.x/eloquent
To efficiently handle large numbers of Eloquent records and prevent memory exhaustion, the chunk method retrieves models in smaller subsets. It accepts a chunk size and a closure, executing a database query for each chunk. This significantly reduces memory usage compared to loading all records at once.
use App\Models\Flight;
use Illuminate\Database\Eloquent\Collection;
Flight::chunk(200, function (Collection $flights) {
foreach ($flights as $flight) {
// ...
}
});
Exclude Models from Pruning with Laravel Artisan Command
Source: https://laravel.com/docs/12.x/eloquent
This code demonstrates how to exclude specific models from the pruning process using the --except option with the model:prune Artisan command. This allows general pruning of detected models while safeguarding particular models from deletion.
Schedule::command('model:prune', [
'--except' => [Address::class, Flight::class],
])->daily();
Install Meilisearch PHP SDK via Composer
Source: https://laravel.com/docs/12.x/scout
Installs the Meilisearch PHP SDK and HTTP factory via Composer, which are essential dependencies for using Meilisearch with Laravel Scout.
composer require meilisearch/meilisearch-php http-interop/http-factory-guzzle
Configure Laravel Echo for Reverb broadcasting (JavaScript, React, Vue)
Source: https://laravel.com/docs/12.x/broadcasting
This configuration initializes Laravel Echo to connect to a Reverb server using the Pusher protocol. It sets the broadcaster, application key, host, port, and TLS settings, enabling real-time event handling in your frontend application. Examples are provided for plain JavaScript, React, and Vue environments.
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'reverb',
key: import.meta.env.VITE_REVERB_APP_KEY,
wsHost: import.meta.env.VITE_REVERB_HOST,
wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,
wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
enabledTransports: ['ws', 'wss'],
});
import { configureEcho } from '@laravel/echo-react';
configureEcho({
broadcaster: 'reverb',
// key: import.meta.env.VITE_REVERB_APP_KEY,
// wsHost: import.meta.env.VITE_REVERB_HOST,
// wsPort: import.meta.env.VITE_REVERB_PORT,
// wssPort: import.meta.env.VITE_REVERB_PORT,
// forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
// enabledTransports: ['ws', 'wss'],
});
import { configureEcho } from '@laravel/echo-vue';
configureEcho({
broadcaster: 'reverb',
// key: import.meta.env.VITE_REVERB_APP_KEY,
// wsHost: import.meta.env.VITE_REVERB_HOST,
// wsPort: import.meta.env.VITE_REVERB_PORT,
// wssPort: import.meta.env.VITE_REVERB_PORT,
// forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
// enabledTransports: ['ws', 'wss'],
});
Create a Paddle customer from a user in PHP
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP snippet illustrates how to create a Paddle customer record without immediately starting a subscription. Calling createAsCustomer() on a billable model instance provisions a customer in Paddle, returning an instance of Laravel\Paddle\Customer. This allows for later subscription management.
$customer = $user->createAsCustomer();
Install Laravel Cashier Package via Composer
Source: https://laravel.com/docs/12.x/billing
This command installs the Laravel Cashier package using Composer, adding it to your project’s dependencies. Cashier facilitates Stripe subscription billing management within Laravel applications.
composer require laravel/cashier
Configure Dusk to Connect to a Custom Selenium Server
Source: https://laravel.com/docs/12.x/dusk
Modify the driver method in your tests/DuskTestCase.php to connect to a custom Selenium server. This example connects to a server at http://localhost:4444/wd/hub and specifies desired capabilities, such as using PhantomJS (though PhantomJS is largely deprecated).
use Facebook\WebDriver\Remote\RemoteWebDriver;
/**
* Create the RemoteWebDriver instance.
*/
protected function driver(): RemoteWebDriver
{
return RemoteWebDriver::create(
'http://localhost:4444/wd/hub', DesiredCapabilities::phantomjs()
);
}
Apply Supervisor Configuration and Start Horizon
Source: https://laravel.com/docs/12.x/horizon
These shell commands are used to update Supervisor’s configuration after changes, and then to start the specifically configured ‘horizon’ process. reread reloads the configuration, update applies pending changes, and start initiates the specified program.
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start horizon
Generating Database Queue Table Migration (Shell)
Source: https://laravel.com/docs/12.x/queues
Provides the Artisan commands required to set up the database queue driver. It includes generating the necessary migration file for the ‘jobs’ table and then running the database migrations.
php artisan make:queue-table
php artisan migrate
Handle Eloquent Events After Database Transaction Commit
Source: https://laravel.com/docs/12.x/eloquent
This PHP code shows an Eloquent observer implementing the ShouldHandleEventsAfterCommit interface. This ensures that the observer’s event handlers only execute after the current database transaction has successfully committed, preventing premature actions on uncommitted data.
<?php
namespace AppObservers;
use AppModelsUser;
use IlluminateContractsEventsShouldHandleEventsAfterCommit;
class UserObserver implements ShouldHandleEventsAfterCommit
{
/**
* Handle the User "created" event.
*/
public function created(User $user): void
{
// ...
}
}
Map Multiple Shared Folders in Homestead.yaml (YAML)
Source: https://laravel.com/docs/12.x/homestead
Optimize performance by mapping individual application folders instead of a single large directory. This configuration shows how to define multiple separate folder mappings within the folders property of Homestead.yaml.
folders:
- map: ~/code/project1
to: /home/vagrant/project1
- map: ~/code/project2
to: /home/vagrant/project2
Swap Subscription Price and Skip Trial (PHP)
Source: https://laravel.com/docs/12.x/billing
Shows how to swap a subscription to a new price while also immediately ending any active trial period. The skipTrial method is chained before the swap call to achieve this behavior.
$user->subscription('default')
->skipTrial()
->swap('price_yearly');
Get Multi-line User Input with Textarea Prompt (PHP)
Source: https://laravel.com/docs/12.x/prompts
The textarea function prompts the user for multi-line text input. These examples show basic usage, how to include placeholder text and informational hints, and how to enforce required input with custom messages.
use function Laravel\Prompts\textarea;
$story = textarea('Tell me a story.');
$story = textarea(
label: 'Tell me a story.',
placeholder: 'This is a story about...',
hint: 'This will be displayed on your profile.'
);
$story = textarea(
label: 'Tell me a story.',
required: true
);
$story = textarea(
label: 'Tell me a story.',
required: 'A story is required.'
);
HTML Asset Referencing and Vite Processing
Source: https://laravel.com/docs/12.x/vite
This HTML example demonstrates the different ways Vite handles asset references. It shows that absolute paths prevent Vite from including assets in the build, while relative paths are correctly processed, rewritten, and versioned by Vite.
<!-- This asset is not handled by Vite and will not be included in the build -->
<img src="/taylor.png" />
<!-- This asset will be re-written, versioned, and bundled by Vite -->
<img src="../../images/abigail.png" />
Utilize Dynamic Eloquent Scopes with Parameters in Laravel Queries
Source: https://laravel.com/docs/12.x/eloquent
After defining a dynamic scope, you can call it and pass the required arguments directly. This allows you to apply parameterized query constraints, such as retrieving users of a specific ‘type’, directly within your Eloquent queries.
$users = User::ofType('admin')->get();
Create Subscription with Specific Trial End Date (PHP)
Source: https://laravel.com/docs/12.x/billing
This example shows how to set a precise end date for a subscription trial using the trialUntil method, which accepts a DateTime instance (e.g., a Carbon instance). This provides more granular control over when the trial period terminates.
use Illuminate\Support\Carbon;
$user->newSubscription('default', 'price_monthly')
->trialUntil(Carbon::now()->addDays(10))
->create($paymentMethod);
Combine Local Eloquent Scopes with Higher-Order OR Operator in Laravel
Source: https://laravel.com/docs/12.x/eloquent
Laravel provides a convenient ‘higher-order’ orWhere method to fluently chain scopes together with an ‘OR’ operator without explicit closures. This simplifies combining scopes for more readable and concise code.
$users = User::popular()->orWhere->active()->get();
Basic Blade Component Rendering Syntax
Source: https://laravel.com/docs/12.x/blade
These Blade examples show the fundamental syntax for rendering Blade components. Components are called using x- followed by the kebab-case name of the component class.
<x-alert/>
<x-user-profile/>
Configure Homestead Services (Enable/Disable) in YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration illustrates how to customize the services running on your Homestead virtual machine by enabling PostgreSQL and disabling MySQL. It modifies the services property in the Homestead.yaml file, controlling which database servers are active.
services:
- enabled:
- 'postgresql'
- disabled:
- 'mysql'
Define a Web Route to a Controller Action (PHP)
Source: https://laravel.com/docs/12.x/routing
This example shows how to register a GET route in the routes/web.php file that dispatches to a specific method (index) within a controller (UserController). These routes are assigned the web middleware group for session and CSRF protection.
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);
Install Postmark Mailer Driver for Symfony/Laravel
Source: https://laravel.com/docs/12.x/mail
This command installs the necessary Composer packages for integrating the Postmark mailer transport with Symfony, which is used by Laravel. It ensures the Postmark driver and HTTP client dependencies are available in the project.
composer require symfony/postmark-mailer symfony/http-client
Apply Stripe Promotion Code to New Laravel Cashier Subscription
Source: https://laravel.com/docs/12.x/billing
This PHP example shows how to apply a Stripe promotion code (using its API ID) when creating a new subscription with Laravel Cashier. The withPromotionCode method associates the specified promotion code with the new subscription before it’s created.
$user->newSubscription('default', 'price_monthly')
->withPromotionCode('promo_code_id')
->create($paymentMethod);
Define Custom Laravel Dusk Browser Macro
Source: https://laravel.com/docs/12.x/dusk
This PHP code demonstrates how to define a custom browser method using Browser::macro within a service provider’s boot method. The example creates a scrollToElement macro that scrolls the browser to a specified HTML element using JavaScript, returning the Browser instance for method chaining.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\Browser;
class DuskServiceProvider extends ServiceProvider
{
/**
* Register Dusk's browser macros.
*/
public function boot(): void
{
Browser::macro('scrollToElement', function (string $element = null) {
$this->script("$('html, body').animate({ scrollTop: $('$element').offset().top }, 0);");
return $this;
});
}
}
Temporarily Mute All Eloquent Model Events
Source: https://laravel.com/docs/12.x/eloquent
This PHP snippet demonstrates how to temporarily disable all events fired by an Eloquent model using the withoutEvents method. It accepts a closure, executing its code without dispatching events, and returns any value from the closure.
use AppModelsUser;
$user = User::withoutEvents(function () {
User::findOrFail(1)->delete();
return User::find(2);
});
Get Laravel Table Overview
Source: https://laravel.com/docs/12.x/database
Provides a detailed overview of an individual database table (e.g., ‘users’), including its columns, types, attributes, keys, and indexes, using the Artisan db:table command.
php artisan db:table users
Swap Subscription Plan Without Billing in Laravel Cashier Paddle
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP example shows how to change a user’s subscription plan without generating any bill for the change. The doNotBill method is used in conjunction with swap.
$user->subscription('default')->doNotBill()->swap($premium = 'pri_456');
Define Minio S3 Buckets in Homestead Configuration
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration allows you to provision Minio-powered S3 buckets directly within your Homestead.yaml file. You can define multiple buckets with specified names and access policies (e.g., public, none, download, upload). After defining, run vagrant reload --provision to apply changes.
buckets:
- name: your-bucket
policy: public
- name: your-private-bucket
policy: none
Create Stripe Webhook using Cashier Artisan Command (Shell)
Source: https://laravel.com/docs/12.x/billing
This Artisan command automatically creates a Stripe webhook configured for Laravel Cashier, listening to all necessary events. It supports customizing the webhook URL, Stripe API version, and initial enabled state, simplifying webhook setup.
php artisan cashier:webhook
php artisan cashier:webhook --url "https://example.com/stripe/webhook"
php artisan cashier:webhook --api-version="2019-12-03"
php artisan cashier:webhook --disabled
Show Laravel Database Overview with Counts and Views
Source: https://laravel.com/docs/12.x/database
Displays a detailed database overview including table row counts and database view details using the Artisan db:show command with the --counts and --views options. Be aware that retrieving this data can be slow on large databases.
php artisan db:show --counts --views
Insert New Eloquent Models using the create Method in Laravel
Source: https://laravel.com/docs/12.x/eloquent
The static create() method allows for mass assignment of attributes to insert a new model in a single statement, returning the newly created model instance. This method requires configuring fillable or guarded properties on your model to prevent mass assignment vulnerabilities.
use App\Models\Flight;
$flight = Flight::create([
'name' => 'London to Paris',
]);
Save Single Eloquent Model Without Dispatching Events
Source: https://laravel.com/docs/12.x/eloquent
This PHP code uses the saveQuietly method to persist changes to an Eloquent model without triggering any associated model events. This is useful when you need to update a model’s state silently.
$user = User::findOrFail(1);
$user->name = 'Victoria Faith';
$user->saveQuietly();
Disable Auto-Incrementing Primary Key in Laravel Eloquent Model
Source: https://laravel.com/docs/12.x/eloquent
Eloquent assumes that primary keys are incrementing integer values. If your model uses a non-incrementing primary key, you must define the public ‘$incrementing’ property and set it to ‘false’.
<?php
class Flight extends Model
{
/**
* Indicates if the model's ID is auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
}
Swap Subscription Price and Invoice Immediately (PHP)
Source: https://laravel.com/docs/12.x/billing
Illustrates how to change a customer’s subscription price and immediately generate an invoice for the change, rather than waiting for the next billing cycle. This is done using the swapAndInvoice method.
$user = User::find(1);
$user->subscription('default')->swapAndInvoice('price_yearly');
Generate a New Laravel Dusk Browser Test
Source: https://laravel.com/docs/12.x/dusk
Use the dusk:make Artisan command to create a new browser test file. The generated test will be placed in the tests/Browser directory, providing a boilerplate for writing your Dusk test scenarios.
php artisan dusk:make LoginTest
Enable Asset Prefetching with Concurrency in Laravel Vite
Source: https://laravel.com/docs/12.x/vite
Instruct Laravel to eagerly prefetch JavaScript and CSS assets during initial page load to reduce UI rendering delays in SPAs. This example sets a maximum concurrency of 3 downloads.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Vite;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
// ...
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Vite::prefetch(concurrency: 3);
}
}
Install Laravel Telescope via Composer
Source: https://laravel.com/docs/12.x/telescope
This Composer command installs the Laravel Telescope package into your project, making it available as a dependency.
composer require laravel/telescope
Install Laravel Pail for Log Tailing
Source: https://laravel.com/docs/12.x/logging
This command installs the Laravel Pail package as a development dependency using Composer. Laravel Pail is a utility designed for real-time log tailing, requiring the PCNTL PHP extension.
composer require --dev laravel/pail
Ensure string starts with a specific value in Laravel Str
Source: https://laravel.com/docs/12.x/strings
The start method adds a single instance of a given value to the beginning of a string if it doesn’t already start with that value. This ensures consistent string prefixes for paths or URLs. It’s available via Laravel’s Illuminate\Support\Str facade.
use Illuminate\Support\Str;
$adjusted = Str::of('this/string')->start('/');
// /this/string
$adjusted = Str::of('/this/string')->start('/');
// /this/string
Compare Laravel Facade and Helper Function for View Generation
Source: https://laravel.com/docs/12.x/facades
This PHP code shows the equivalence between using a Laravel facade (Illuminate\Support\Facades\View::make) and a helper function (view()) to generate a view. Both achieve the same result for rendering the ‘profile’ view.
return Illuminate\Support\Facades\View::make('profile');
return view('profile');
Retrieve Laravel session data using a Request instance
Source: https://laravel.com/docs/12.x/session
This PHP example demonstrates how to retrieve session data within a Laravel controller method. By type-hinting Illuminate\Http\Request, you can access the session instance and use the get() method to fetch a value by its key.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\View\View;
class UserController extends Controller
{
/**
* Show the profile for the given user.
*/
public function show(Request $request, string $id): View
{
$value = $request->session()->get('key');
// ...
$user = $this->users->find($id);
return view('user.profile', ['user' => $user]);
}
}
Install Vite Plugin for Subresource Integrity (SRI)
Source: https://laravel.com/docs/12.x/vite
To enable Subresource Integrity (SRI) for your assets with Vite, you first need to install the vite-plugin-manifest-sri NPM package. This command adds the plugin as a development dependency to your project.
npm install --save-dev vite-plugin-manifest-sri
Define Mass Assignable Attributes with $fillable Property in PHP
Source: https://laravel.com/docs/12.x/eloquent
Illustrates how to define the $fillable property on an Eloquent model, specifying which attributes are allowed to be mass assigned. This is a crucial security measure to prevent unexpected database column changes from malicious user input.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = ['name'];
}
Access the parallel testing token in Laravel
Source: https://laravel.com/docs/12.x/testing
This PHP snippet retrieves the unique process token for the current parallel test execution. The token can be used to segment resources or differentiate between parallel processes within application test code, for instance, to ensure data isolation.
$token = ParallelTesting::token();
Create Multiple Browser Instances for Concurrent Testing in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This example illustrates how to create and use multiple browser instances concurrently within a single Laravel Dusk test. It demonstrates logging in two different users, visiting a page, interacting with an element (typing a message), and asserting content, useful for testing real-time interactions like chat applications.
$this->browse(function (Browser $first, Browser $second) {
$first->loginAs(User::find(1))
->visit('/home')
->waitForText('Message');
$second->loginAs(User::find(2))
->visit('/home')
->waitForText('Message')
->type('message', 'Hey Taylor')
->press('Send');
$first->waitForText('Hey Taylor')
->assertSee('Jeffrey Way');
});
Install Vite React Plugin
Source: https://laravel.com/docs/12.x/vite
Installs the @vitejs/plugin-react package as a development dependency. This plugin is necessary for integrating React.js with Vite in a Laravel project, providing support for JSX and React Fast Refresh.
npm install --save-dev @vitejs/plugin-react
Define Multiple Reverb Applications in config/reverb.php
Source: https://laravel.com/docs/12.x/reverb
Configure a single Reverb installation to serve WebSocket connectivity for multiple distinct applications by defining additional entries within the apps array in your config/reverb.php file. Each application requires its own unique app_id.
'apps' => [
[
'app_id' => 'my-app-one',
// ...
],
[
'app_id' => 'my-app-two',
// ...
],
],
Start Laravel Horizon Processes (Shell)
Source: https://laravel.com/docs/12.x/horizon
This Artisan command initiates all configured worker processes for the current environment as defined in the config/horizon.php file. It’s the primary way to start the Horizon daemon.
php artisan horizon
Configure Laravel Octane with FrankenPHP Dockerfile
Source: https://laravel.com/docs/12.x/octane
This Dockerfile serves as a starting point for containerizing a Laravel Octane application using FrankenPHP. It extends the official dunglas/frankenphp image, installs essential PHP extensions like pcntl, copies the application code, and sets the entry point to run Octane’s FrankenPHP server.
FROM dunglas/frankenphp
RUN install-php-extensions \
pcntl
# Add other PHP extensions here...
COPY . /app
ENTRYPOINT ["php", "artisan", "octane:frankenphp"]
Install Laravel Scout via Composer
Source: https://laravel.com/docs/12.x/scout
Install the Laravel Scout package into your project using Composer. This command adds the necessary files and dependencies to integrate Scout.
composer require laravel/scout
Swap Prices with Quantities in Laravel Cashier Subscription (PHP)
Source: https://laravel.com/docs/12.x/billing
This example illustrates how to specify subscription item options, such as quantities, when swapping prices. It uses an array of key/value pairs passed to the swap method to set a specific quantity for ‘price_pro’ while including ‘price_chat’ without explicit quantity.
$user = User::find(1);
$user->subscription('default')->swap([
'price_pro' => ['quantity' => 5],
'price_chat'
]);
Publish Assets and Configuration Files from Laravel Package
Source: https://laravel.com/docs/12.x/packages
These snippets demonstrate how to define and publish various assets and configuration files from a Laravel package. The PHP code shows how to register public assets and tagged file groups within a service provider, while the shell commands illustrate how users can publish these resources using vendor:publish with tags or provider names. This allows for selective or forced publishing of package files.
/**
* Bootstrap any package services.
*/
public function boot(): void
{
$this->publishes([
__DIR__.'/../public' => public_path('vendor/courier'),
], 'public');
}
/**
* Bootstrap any package services.
*/
public function boot(): void
{
$this->publishes([
__DIR__.'/../config/package.php' => config_path('package.php')
], 'courier-config');
$this->publishesMigrations([
__DIR__.'/../database/migrations/' => database_path('migrations')
], 'courier-migrations');
}
php artisan vendor:publish --tag=public --force
php artisan vendor:publish --tag=courier-config
php artisan vendor:publish --provider="Your\Package\ServiceProvider"
Set Custom Primary Key Data Type in Laravel Eloquent Model
Source: https://laravel.com/docs/12.x/eloquent
If your model’s primary key is not an integer (e.g., a UUID or ULID), you should define the protected ‘$keyType’ property and set its value to ‘string’ to ensure correct handling.
<?php
class Flight extends Model
{
/**
* The data type of the primary key ID.
*
* @var string
*/
protected $keyType = 'string';
}
Generate Laravel Eloquent Global Scope Class
Source: https://laravel.com/docs/12.x/eloquent
Shows how to generate a new global scope class using the Artisan make:scope command. This command creates a new PHP file in your application’s app/Models/Scopes directory for defining custom global query constraints.
php artisan make:scope AncientScope
Customize Suggest Prompt with Placeholder, Default, and Hint (Laravel PHP)
Source: https://laravel.com/docs/12.x/prompts
Shows how to enhance the user experience of the suggest function by adding a placeholder for example input, a default value, and an hint to provide additional context or information to the user.
$name = suggest(
label: 'What is your name?',
options: ['Taylor', 'Dayle'],
placeholder: 'E.g. Taylor',
default: $user?->name,
hint: 'This will be displayed on your profile.'
);
Preview SQL for Laravel Database Migrations
Source: https://laravel.com/docs/12.x/migrations
This shell command allows you to preview the SQL statements that would be executed by your Laravel migrations without actually applying them to the database. The --pretend flag is useful for inspecting the changes before committing them.
php artisan migrate --pretend
Customize a guest checkout session with a promotion code in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP example shows how to customize a guest checkout session by applying a promotion code using the withPromotionCode() method on the Cashier CheckoutBuilder instance. It sets up a Laravel route to create a guest checkout session for a product with a specified price ID, including success and cancel URLs, and applies ‘promo-code’ during checkout.
use Illuminate\Http\Request;
use Laravel\Cashier\Checkout;
Route::get('/product-checkout', function (Request $request) {
return Checkout::guest()
->withPromotionCode('promo-code')
->create('price_tshirt', [
'success_url' => route('your-success-route'),
'cancel_url' => route('your-cancel-route'),
]);
});
Install Typesense PHP SDK via Composer
Source: https://laravel.com/docs/12.x/scout
Installs the Typesense PHP SDK via Composer, a necessary step for integrating Typesense as a search engine with Laravel Scout.
composer require typesense/typesense-php
Add Nginx fastcgi_param to Homestead Site in YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration allows adding custom Nginx fastcgi_param values to a Homestead site via the params directive. It takes a list of key-value pairs that are then passed to the FastCGI process, useful for setting custom environment variables or specific PHP-FPM settings.
sites:
- map: homestead.test
to: /home/vagrant/project1/public
params:
- key: FOO
value: BAR
Update Laravel Cashier Subscription Quantity Without Prorating
Source: https://laravel.com/docs/12.x/billing
This example shows how to update a subscription’s quantity to a specific value (e.g., 10) without applying proration to the charges. This is achieved by chaining the noProrate() method before updateQuantity().
$user->subscription('default')->noProrate()->updateQuantity(10);
Install Laravel Precognition React Frontend Helpers (NPM)
Source: https://laravel.com/docs/12.x/precognition
This command installs the necessary frontend helpers for integrating Laravel Precognition with React applications. It uses npm to add the laravel-precognition-react package to your project’s devDependencies or dependencies, making the useForm hook available.
npm install laravel-precognition-react
Install Laravel Socialite via Composer
Source: https://laravel.com/docs/12.x/socialite
This command installs the Laravel Socialite package into your project’s dependencies using Composer, making it available for use in your Laravel application.
composer require laravel/socialite
Update Eloquent Model Attributes with save method (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This snippet demonstrates how to update a single attribute of an existing Eloquent model. It retrieves the model by its ID, modifies an attribute, and then calls the save method. The updated_at timestamp is automatically updated by Eloquent.
use App\Models\Flight;
$flight = Flight::find(1);
$flight->name = 'Paris to London';
$flight->save();
Use Custom Keyboard Macros in Laravel Dusk PHP
Source: https://laravel.com/docs/12.x/dusk
This PHP example demonstrates how to use the previously defined ‘copy’ and ‘paste’ keyboard macros within a Laravel Dusk browser test. It shows how to interact with elements and apply macros via the withKeyboard method for complex keyboard sequences.
$browser->click('@textarea')
->withKeyboard(fn (Keyboard $keyboard) => $keyboard->copy())
->click('@another-textarea')
->withKeyboard(fn (Keyboard $keyboard) => $keyboard->paste());
Perform Fluent Keyboard Interactions with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
Dusk’s withKeyboard method enables fluent, complex keyboard interactions using the Laravel\Dusk\Keyboard class. It provides methods like press, release, type, and pause for precise control over key events.
use Laravel\Dusk\Keyboard;
$browser->withKeyboard(function (Keyboard $keyboard) {
$keyboard->press('c')
->pause(1000)
->release('c')
->type(['c', 'e', 'o']);
});
Install Laravel Precognition Vue Frontend Helpers
Source: https://laravel.com/docs/12.x/precognition
This shell command installs the laravel-precognition-vue package via NPM. This package provides the essential frontend helpers and composables required for integrating Laravel Precognition’s live validation features within Vue.js applications.
npm install laravel-precognition-vue
Include Soft Deleted Models in Laravel Eloquent Queries
Source: https://laravel.com/docs/12.x/eloquent
This code demonstrates how to include soft-deleted models in Eloquent query results using the withTrashed method. It can be applied directly to a model query or to a relationship query to retrieve all models, regardless of their soft-deletion status.
use App\Models\Flight;
$flights = Flight::withTrashed()
->where('account_id', 1)
->get();
$flight->history()->withTrashed()->get();
Fit Browser Window to Content Size with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This snippet shows how to use the fitContent method to resize the browser window to precisely match the dimensions of its rendered content. This can be helpful for capturing screenshots that perfectly frame the page content without extra whitespace.
$browser->fitContent();
Perform Eloquent Upsert Operation in PHP
Source: https://laravel.com/docs/12.x/eloquent
Illustrates the use of Eloquent’s upsert method to atomically update or create multiple records in a single operation. It takes an array of values, columns that uniquely identify records, and columns to update if a match is found.
Flight::upsert([
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], uniqueBy: ['departure', 'destination'], update: ['price']);
Define Eloquent Scopes with Pending Attributes for Model Creation in Laravel
Source: https://laravel.com/docs/12.x/eloquent
This snippet demonstrates how to use the withAttributes method within a scope. This method adds where conditions to the query based on the given attributes and also applies these attributes to any models created via that scope, ensuring consistency.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Scope the query to only include drafts.
*/
#[Scope]
protected function draft(Builder $query): void
{
$query->withAttributes([
'hidden' => true,
]);
}
}
Make a Simple Charge using Laravel Cashier and Request User (PHP)
Source: https://laravel.com/docs/12.x/billing
Demonstrates how to perform a one-time charge against the authenticated user’s payment method. It requires an Illuminate\Http\Request object and a paymentMethodId to process the transaction.
use Illuminate\Http\Request;
Route::post('/purchase', function (Request $request) {
$stripeCharge = $request->user()->charge(
100, $request->paymentMethodId
);
// ...
});
Configure Pusher environment variables in Laravel
Source: https://laravel.com/docs/12.x/broadcasting
Defines the necessary environment variables in the .env file for Pusher and VITE to enable Laravel Echo to connect to the Pusher service. These variables include application ID, key, secret, host, port, scheme, and cluster.
PUSHER_APP_ID="your-pusher-app-id"
PUSHER_APP_KEY="your-pusher-key"
PUSHER_APP_SECRET="your-pusher-secret"
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME="https"
PUSHER_APP_CLUSTER="mt1"
VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
Check Laravel Cashier Coupon Type and Get Discount Amount
Source: https://laravel.com/docs/12.x/billing
This PHP snippet demonstrates how to determine if a Laravel Cashier coupon offers a percentage-based or fixed-amount discount. It uses isPercentage(), percentOff(), and amountOff() methods to display the appropriate discount value.
if ($coupon->isPercentage()) {
return $coupon->percentOff().'%'; // 21.5%
} else {
return $coupon->amountOff(); // $5.99
}
Install Dompdf Library for Invoice Rendering
Source: https://laravel.com/docs/12.x/billing
Before generating invoice PDFs with Laravel Cashier, install the ‘dompdf/dompdf’ library using Composer. This package serves as the default renderer for creating PDF invoices within Cashier.
composer require dompdf/dompdf
Install spatie/fork Package for Laravel Concurrency
Source: https://laravel.com/docs/12.x/concurrency
To use the fork driver for improved concurrency performance in Laravel, you need to install the spatie/fork package. This command adds the package to your project’s dependencies.
composer require spatie/fork
Running Laravel Queue Worker with Priority (Shell)
Source: https://laravel.com/docs/12.x/queues
Illustrates how to start a Laravel queue worker using the Artisan command. This command allows specifying which queues to process, giving priority to certain queues (e.g., ‘high’) over others (‘default’).
php artisan queue:work --queue=high,default
Create a One-off Charge using InvoiceFor (PHP)
Source: https://laravel.com/docs/12.x/billing
Shows an alternative method, invoiceFor, to make a direct one-off charge against the customer’s default payment method. While functional, it’s recommended to use invoicePrice or tabPrice for better analytics.
$user->invoiceFor('One Time Fee', 500);
Define Laravel Eloquent Anonymous Global Scope
Source: https://laravel.com/docs/12.x/eloquent
Explains how to define a global scope using a closure, which is suitable for simpler scopes that do not warrant a separate class. This method uses the addGlobalScope method with a custom scope name and a closure to apply query constraints.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The "booted" method of the model.
*/
protected static function booted(): void
{
static::addGlobalScope('ancient', function (Builder $builder) {
$builder->where('created_at', '<', now()->subYears(2000));
});
}
}
Lazy load Eloquent models as a stream with lazy in PHP
Source: https://laravel.com/docs/12.x/eloquent
The lazy method efficiently processes large datasets by executing queries in chunks, similar to chunk. However, it returns a flattened LazyCollection, allowing interaction with the results as a single, continuous stream, which is useful for memory-efficient processing without explicit chunk callbacks.
use App\Models\Flight;
foreach (Flight::lazy() as $flight) {
// ...
}
Maximize Browser Window with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This snippet demonstrates the maximize method, which expands the browser window to fill the entire screen. This is useful for ensuring content displays correctly at maximum resolution or for scenarios requiring full-screen views.
$browser->maximize();
Perform Basic Model Search with Laravel Scout (PHP)
Source: https://laravel.com/docs/12.x/scout
Illustrates how to initiate a search on an Eloquent model using Scout’s search method and retrieve the matching Eloquent models. Includes an example of integrating search into a Laravel route.
use App\Models\Order;
$orders = Order::search('Star Trek')->get();
use App\Models\Order;
use Illuminate\Http\Request;
Route::get('/search', function (Request $request) {
return Order::search($request->search)->get();
});
Example Laravel Model Broadcast Event Payload (JSON)
Source: https://laravel.com/docs/12.x/broadcasting
This JSON object represents the typical payload structure of a Laravel model broadcast event. It includes the model properties (like ID and title) and a socket identifier, demonstrating the data sent to client-side applications.
{
"model": {
"id": 1,
"title": "My first post"
...
},
...
"socket": "someSocketId"
}
Define Function with Comprehensive PHPDoc Block in PHP
Source: https://laravel.com/docs/12.x/contributions
This example demonstrates a complete PHPDoc block for a PHP function, including @param for arguments, @return for the return type, and @throws for potential exceptions. It highlights the specific spacing required for @param attributes to ensure consistent documentation style.
/**
* Register a binding with the container.
*
* @param string|array $abstract
* @param \Closure|string|null $concrete
* @param bool $shared
* @return void
*
* @throws \Exception
*/
public function bind($abstract, $concrete = null, $shared = false)
{
// ...
}
Perform Mass Updates on Eloquent Models (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This snippet shows how to update multiple Eloquent models that match a given query. It uses where clauses to filter records and then applies updates to an array of column-value pairs using the update method. Note that model events are not fired during mass updates.
Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
POST /register
Source: https://laravel.com/docs/12.x/fortify
Registers a new user with the provided credentials. This endpoint handles user creation and initial authentication.
## POST /register
### Description
Registers a new user account with the application. Requires user details such as name, email (or username), and a confirmed password.
### Method
POST
### Endpoint
/register
### Parameters
#### Request Body
- **name** (string) - Required - The full name of the new user.
- **email** (string) - Required - The unique email address or username for the new user, depending on 'username' configuration.
- **password** (string) - Required - The desired password for the new user. Minimum length and complexity typically apply.
- **password_confirmation** (string) - Required - Confirmation of the password, must match the 'password' field.
### Request Example
{
"name": "John Doe",
"email": "john.doe@example.com",
"password": "secretpassword",
"password_confirmation": "secretpassword"
}
### Response
#### Success Response (201 Created for XHR / Redirect for web)
On successful registration, for XHR requests, a 201 HTTP response is returned. For web requests, the user is redirected to the configured 'home' URI.
#### Error Response (422 Unprocessable Entity for XHR / Redirect for web)
If the registration data is invalid (e.g., email already exists, passwords don't match, invalid format), for XHR requests, a 422 HTTP response is returned with validation errors. For web requests, the user is redirected back to the registration screen with errors.
Install Vite Vue Plugin
Source: https://laravel.com/docs/12.x/vite
Installs the @vitejs/plugin-vue package as a development dependency. This plugin is essential for integrating Vue.js with Vite in a Laravel project, enabling support for Vue Single File Components.
npm install --save-dev @vitejs/plugin-vue
Listen for Client Events with Echo’s listenForWhisper method (JS, React, Vue)
Source: https://laravel.com/docs/12.x/broadcasting
This snippet demonstrates how to listen for client-side events that were broadcast using the whisper method. It uses listenForWhisper to subscribe to specific client events like ‘typing’ notifications on a private channel. Examples cover plain JavaScript, React, and Vue implementations.
Echo.private(`chat.${roomId}`).listenForWhisper('typing', (e) => {
console.log(e.name);
});
import { useEcho } from '@laravel/echo-react';
const { channel } = useEcho(`chat.${roomId}`, ['update'], (e) => {
console.log('Chat event received:', e);
});
channel().listenForWhisper('typing', (e) => {
console.log(e.name);
});
<script setup lang="ts">
import { useEcho } from '@laravel/echo-vue';
const { channel } = useEcho(`chat.${roomId}`, ['update'], (e) => {
console.log('Chat event received:', e);
});
channel().listenForWhisper('typing', (e) => {
console.log(e.name);
});
</script>
Ensure String Starts With a Value in PHP (Str::start)
Source: https://laravel.com/docs/12.x/strings
The Str::start method adds a single instance of a given value to the beginning of a string, but only if the string does not already start with that value. This ensures a consistent prefix for strings.
use Illuminate\Support\Str;
$adjusted = Str::start('this/string', '/');
// /this/string
$adjusted = Str::start('/this/string', '/');
// /this/string
Run Laravel Envoy Binary
Source: https://laravel.com/docs/12.x/envoy
Executes the Envoy command-line tool from your project’s vendor directory. This is how you invoke Envoy tasks after installation, allowing you to run defined deployment or server maintenance tasks.
php vendor/bin/envoy
Combine Local Eloquent Scopes with OR Operator Using Closures in Laravel
Source: https://laravel.com/docs/12.x/eloquent
This snippet demonstrates how to combine multiple local scopes using an orWhere clause with a closure. This approach is necessary when you need to logically group conditions with an ‘OR’ operator, ensuring correct query construction.
$users = User::popular()->orWhere(function (Builder $query) {
$query->active();
})->get();
Define Default Attributes for Laravel Eloquent Models
Source: https://laravel.com/docs/12.x/eloquent
This snippet illustrates how to define default attribute values for a Laravel Eloquent model by setting the $attributes protected property. The values should be in their raw, storable format, mimicking how they would appear if directly read from the database.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
'options' => '[]',
'delayed' => false,
];
}
Filter Eloquent Collection with reject method in PHP
Source: https://laravel.com/docs/12.x/eloquent
This snippet demonstrates how to use the reject method on an Eloquent Collection to filter out models based on a given condition. It takes a closure and removes items for which the closure returns true. This is useful for dynamically filtering retrieved records.
$flights = Flight::where('destination', 'Paris')->get();
$flights = $flights->reject(function (Flight $flight) {
return $flight->cancelled;
});
Apply ‘verified’ Middleware to Protect Routes in Laravel
Source: https://laravel.com/docs/12.x/starter-kits
After implementing email verification, use the verified middleware to restrict access to specific routes until the user’s email address has been confirmed. This ensures that only verified users can access protected sections of your application.
Route::middleware(['auth', 'verified'])->group(function () {
Route::get('dashboard', function () {
return Inertia::render('dashboard');
})->name('dashboard');
});
Install Resend PHP SDK for Laravel Mailer
Source: https://laravel.com/docs/12.x/mail
This Composer command installs the official Resend PHP SDK, which is required to use Resend as an email driver in a Laravel application. It fetches the necessary library to interact with the Resend API.
composer require resend/resend-php
Prevent Eloquent withAttributes from Adding WHERE Conditions in Laravel Scopes
Source: https://laravel.com/docs/12.x/eloquent
To use withAttributes solely for applying attributes during model creation without adding them as where conditions to the query, set the asConditions argument to false. This offers more control over how pending attributes interact with the query builder.
$query->withAttributes([
'hidden' => true,
], asConditions: false);
Enable Webdriver Feature for Laravel Dusk in Homestead
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration enables the webdriver feature in Homestead, which is essential for running Laravel Dusk tests. By adding webdriver: true under the features section of your Homestead.yaml file, you prepare your Homestead environment to execute browser-driven tests.
features:
- webdriver: true
Integrate shadcn-vue Switch Component in Vue
Source: https://laravel.com/docs/12.x/starter-kits
This Vue template code snippet shows how to import and use a published shadcn-vue Switch component within a Vue component. It assumes the component has been successfully published to the specified path @/Components/ui/switch and uses the <script setup> syntax.
<script setup lang="ts">
import { Switch } from '@/Components/ui/switch';
</script>
<template>
<div>
<Switch />
</div>
</template>
Check for Expired Subscription Trial (PHP)
Source: https://laravel.com/docs/12.x/billing
These examples show how to check if a user’s trial period for a specific subscription has already expired using the hasExpiredTrial method. This can be performed on both the user instance and the subscription instance to verify past trial status.
if ($user->hasExpiredTrial('default')) {
// ...
}
if ($user->subscription('default')->hasExpiredTrial()) {
// ...
}
Make a Simple Charge with Custom Stripe Options (PHP)
Source: https://laravel.com/docs/12.x/billing
Illustrates how to pass an array of custom options to the underlying Stripe charge creation API when using the charge method. These options can include specific Stripe parameters like metadata or custom descriptions.
$user->charge(100, $paymentMethod, [
'custom_option' => $value,
]);
Create Subscription with Multiple Prices and Quantities in Laravel
Source: https://laravel.com/docs/12.x/cashier-paddle
Illustrates subscribing a user to multiple products, some with specified quantities, by passing an associative array of price IDs and quantities to the subscribe method. This allows for flexible product billing.
$user = User::find(1);
$checkout = $user->subscribe('default', ['price_monthly', 'price_chat' => 5]);
Run Laravel Dusk Browser Tests (Shell)
Source: https://laravel.com/docs/12.x/dusk
Execute the php artisan dusk command to initiate all your Laravel Dusk browser tests. This command will launch a browser (typically Chrome via ChromeDriver) and run your defined Dusk test scenarios.
php artisan dusk
Wait for basic JavaScript events in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
The waitForEvent method pauses test execution until a specified JavaScript event occurs, attaching the listener to the current scope (body by default). This example shows waiting for the ‘load’ event.
$browser->waitForEvent('load');
Show Specific Laravel Database Overview
Source: https://laravel.com/docs/12.x/database
Displays an overview of a specified database connection (e.g., ‘pgsql’) using the Artisan db:show command with the --database option. This allows inspecting non-default connections.
php artisan db:show --database=pgsql
Test Model Pruning with Pretend Option in Laravel Artisan
Source: https://laravel.com/docs/12.x/eloquent
This shell command shows how to test the prunable query logic without actually deleting records. The --pretend option makes the model:prune command report how many records would be pruned if the command were to actually run, aiding in verification.
php artisan model:prune --pretend
Customize Subscription Checkout URLs in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This example shows how to configure custom success and cancellation URLs for a Laravel Cashier subscription checkout session. After the customer completes or cancels the checkout on Stripe, they will be redirected to the specified application routes for further processing.
use Illuminate\Http\Request;
Route::get('/subscription-checkout', function (Request $request) {
return $request->user()
->newSubscription('default', 'price_monthly')
->checkout([
'success_url' => route('your-success-route'),
'cancel_url' => route('your-cancel-route'),
]);
});
Automate Laravel Pint Linting with GitHub Actions Workflow
Source: https://laravel.com/docs/12.x/pint
This GitHub Actions workflow defines a CI job to automatically run Laravel Pint on pushes to the repository. It checks out code, sets up PHP with Pint, runs Pint, and commits any fixed files back to the repository, requiring ‘Read and write permissions’ for workflows.
name: Fix Code Style
on: [push]
jobs:
lint:
runs-on: ubuntu-latest
strategy:
fail-fast: true
matrix:
php: [8.4]
steps:
- name: Checkout code
uses: actions/checkout@v5
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
tools: pint
- name: Run Pint
run: pint
- name: Commit linted files
uses: stefanzweifel/git-auto-commit-action@v6
Example Laravel broadcast data payload in JSON
Source: https://laravel.com/docs/12.x/broadcasting
This JSON object illustrates the default data payload structure for a Laravel broadcast event. When an event is broadcast, all its public properties are automatically serialized into JSON, allowing JavaScript applications to access this data.
{
"user": {
"id": 1,
"name": "Patrick Stewart"
...
}
}
Listen to public events using useEchoPublic hook (React/Vue)
Source: https://laravel.com/docs/12.x/broadcasting
This example shows how to use the useEchoPublic hook in React or Vue components to listen for events on public channels. Similar to useEcho, this hook simplifies the process of subscribing to and managing publicly broadcasted events within your component’s lifecycle.
import { useEchoPublic } from '@laravel/echo-react';
useEchoPublic('posts', 'PostPublished', (e) => {
console.log(e.post);
});
<script setup lang="ts">
import { useEchoPublic } from '@laravel/echo-vue';
useEchoPublic('posts', 'PostPublished', (e) => {
console.log(e.post);
});
</script>
Capture Real-time Asynchronous Process Output with PHP Closure
Source: https://laravel.com/docs/12.x/processes
This PHP example shows how to capture real-time output from an asynchronous process by providing a closure to the start method. The closure receives the output type (stdout or stderr) and the output string, allowing immediate processing or logging of output as it occurs without needing to poll.
$process = Process::start('bash import.sh', function (string $type, string $output) {
echo $output;
});
$result = $process->wait();
Update Individual Price Quantities in Laravel Cashier Subscription (PHP)
Source: https://laravel.com/docs/12.x/billing
This example shows how to update quantities for individual prices within a multi-product subscription. It uses incrementQuantity, decrementQuantity, and updateQuantity methods, passing the price ID as an argument to target specific items.
$user = User::find(1);
$user->subscription('default')->incrementQuantity(5, 'price_chat');
$user->subscription('default')->decrementQuantity(3, 'price_chat');
$user->subscription('default')->updateQuantity(10, 'price_chat');
Install Laravel Sanctum using Artisan Command
Source: https://laravel.com/docs/12.x/sanctum
This shell command is used to install Laravel Sanctum within a Laravel project. It sets up the necessary files, including database migrations and configuration, to enable API and SPA authentication functionalities.
php artisan install:api
Retrieve Data from Redis with Laravel Facade get Method
Source: https://laravel.com/docs/12.x/redis
This PHP snippet illustrates how to interact with Redis using the Redis facade in a Laravel controller to retrieve data. It demonstrates calling the dynamic get method, which directly maps to the Redis GET command, to fetch a user profile based on an ID. The result is then passed to a view.
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Redis;
use Illuminate\View\View;
class UserController extends Controller
{
/**
* Show the profile for the given user.
*/
public function show(string $id): View
{
return view('user.profile', [
'user' => Redis::get('user:profile:'.$id)
]);
}
}
Perform Basic Product Checkout with Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This code snippet demonstrates how to initiate a Stripe Checkout session for an existing product in your Stripe dashboard using its Price ID. The checkout method is called on the billable model (e.g., a user) and redirects the customer to Stripe’s checkout page.
use IlluminateHttpRequest;
Route::get('/product-checkout', function (Request $request) {
return $request->user()->checkout('price_tshirt');
});
Create a Paddle customer with custom options in PHP
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP example shows how to create a Paddle customer while passing additional parameters to the Paddle API. The createAsCustomer() method accepts an optional $options array, allowing customization of the customer creation process beyond default values. This is useful for specific Paddle API requirements.
$customer = $user->createAsCustomer($options);
Implement Stripe Checkout for One-Time Product Purchases in Laravel
Source: https://laravel.com/docs/12.x/billing
This Laravel route example shows how to integrate Stripe Checkout for selling non-recurring, single-charge products using Cashier. The checkout method redirects the customer to Stripe to complete the payment, automatically creating a Stripe customer if needed, and then redirects them back to specified success or cancel URLs in your application.
use Illuminate\Http\Request;
Route::get('/checkout', function (Request $request) {
$stripePriceId = 'price_deluxe_album';
$quantity = 1;
return $request->user()->checkout([$stripePriceId => $quantity], [
'success_url' => route('checkout-success'),
'cancel_url' => route('checkout-cancel'),
]);
})->name('checkout');
Route::view('/checkout/success', 'checkout.success')->name('checkout-success');
Route::view('/checkout/cancel', 'checkout.cancel')->name('checkout-cancel');
Find a specific payment method by ID (Laravel Cashier)
Source: https://laravel.com/docs/12.x/billing
This PHP example demonstrates how to find a particular payment method associated with a billable model by its identifier using Laravel Cashier’s findPaymentMethod() method. This allows direct access to a known payment method.
$paymentMethod = $user->findPaymentMethod($paymentMethodId);
Define Local Eloquent Scopes in Laravel Models
Source: https://laravel.com/docs/12.x/eloquent
This code illustrates how to define reusable local scopes within an Eloquent model using the #[Scope] attribute. These scopes encapsulate common query constraints, such as filtering for ‘popular’ or ‘active’ users, promoting code reusability and readability.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Scope a query to only include popular users.
*/
#[Scope]
protected function popular(Builder $query): void
{
$query->where('votes', '>', 100);
}
/**
* Scope a query to only include active users.
*/
#[Scope]
protected function active(Builder $query): void
{
$query->where('active', 1);
}
}
Enable Automatic Database Backups in Homestead
Source: https://laravel.com/docs/12.x/homestead
This configuration snippet shows how to enable automatic database backups in Homestead. Adding backup: true to your Homestead.yaml file ensures databases are exported to .backup/mysql_backup and .backup/postgres_backup directories when the vagrant destroy command is executed. This feature requires Vagrant 2.1.0 or greater, or the vagrant-triggers plug-in.
backup: true
Get Raw Rendered View Contents in Laravel Test
Source: https://laravel.com/docs/12.x/http-tests
This example shows how to retrieve the raw, rendered HTML content of a view in a test. By casting the Illuminate\Testing\TestView instance returned by $this->view() to a string, you can access the full output for further inspection or custom assertions.
$contents = (string) $this->view('welcome');
POST /user/two-factor-authentication
Source: https://laravel.com/docs/12.x/fortify
This endpoint is used to initiate the two-factor authentication setup process for a user. Upon success, the user is redirected or a 200 HTTP response is returned for XHR requests, indicating that 2FA is now enabled but requires confirmation.
## POST /user/two-factor-authentication
### Description
Initiates the two-factor authentication setup for the authenticated user. This step enables 2FA but requires subsequent confirmation with a valid TOTP code.
### Method
POST
### Endpoint
/user/two-factor-authentication
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
{}
### Response
#### Success Response (200)
For XHR requests, a 200 HTTP response is returned. For standard requests, the user is redirected and the `status` session variable is set to `two-factor-authentication-enabled`.
#### Response Example
{}
Disable Automatic Timestamps for Laravel Eloquent Model
Source: https://laravel.com/docs/12.x/eloquent
This PHP code snippet shows how to prevent Eloquent from automatically managing created_at and updated_at columns on a model. By setting the $timestamps property to false, these timestamp fields will no longer be updated during model creation or modification.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
}
Install Laravel Octane and its configuration
Source: https://laravel.com/docs/12.x/octane
Install the Laravel Octane package via Composer and then publish its configuration file using the Artisan command. This sets up Octane for use in your Laravel application.
composer require laravel/octane
php artisan octane:install
Forward Additional Ports in Homestead YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration in Homestead.yaml specifies additional port forwards from the host machine to the Vagrant box. It allows mapping custom ports, including specifying the protocol (e.g., UDP), for services running inside the VM. A re-provision is required after changes.
ports:
- send: 50000
to: 5000
- send: 7777
to: 777
protocol: udp
Interact with a Laravel Dusk component using the component() method
Source: https://laravel.com/docs/12.x/dusk
This snippet shows an alternative way to interact with a Dusk component by retrieving a browser instance scoped to the component. This allows direct method calls on the component instance after it’s been initialized through the component method of the main Browser instance, offering a different syntax for component interaction.
$datePicker = $browser->component(new DatePickerComponent);
$datePicker->selectDate(2019, 1, 30);
$datePicker->assertSee('January');
Create Subscription with Trial Days (PHP)
Source: https://laravel.com/docs/12.x/billing
This code demonstrates how to create a new subscription with a specified trial duration (e.g., 10 days) using the trialDays method. It requires a payment method ID upfront. Cashier will instruct Stripe to delay billing until the trial ends, and it will overwrite any default trial period configured in Stripe for the price.
use Illuminate\Http\Request;
Route::post('/user/subscribe', function (Request $request) {
$request->user()->newSubscription('default', 'price_monthly')
->trialDays(10)
->create($request->paymentMethodId);
// ...
});
Install Laravel Precognition for React and Inertia
Source: https://laravel.com/docs/12.x/precognition
This shell command installs the specific laravel-precognition-react-inertia package via npm. This library provides Inertia-compatible form helpers and validation features for React applications.
npm install laravel-precognition-react-inertia
Install Symfony Brevo Mailer with Composer
Source: https://laravel.com/docs/12.x/mail
This shell command installs the necessary Composer packages (symfony/brevo-mailer and symfony/http-client) to integrate the Brevo (formerly Sendinblue) mailer into a Laravel application, enabling support for this Symfony transport.
composer require symfony/brevo-mailer symfony/http-client
Install Laravel Horizon Composer Package
Source: https://laravel.com/docs/12.x/horizon
This command installs the Laravel Horizon package into your project using Composer, the PHP package manager. It adds Horizon’s dependencies to your composer.json file and downloads the necessary files.
composer require laravel/horizon
Configure ChromeDriver Port in Laravel Dusk (PHP)
Source: https://laravel.com/docs/12.x/dusk
Modify the driver() method in tests/DuskTestCase.php to specify a custom port for ChromeDriver if it’s running on a port other than the default 9515. This ensures Dusk can connect correctly to your manually started ChromeDriver instance.
use Facebook\WebDriver\Remote\RemoteWebDriver;
/**
* Create the RemoteWebDriver instance.
*/
protected function driver(): RemoteWebDriver
{
return RemoteWebDriver::create(
'http://localhost:9515', DesiredCapabilities::chrome()
);
}
Publish Laravel Cashier Configuration File
Source: https://laravel.com/docs/12.x/billing
This Artisan command publishes Cashier’s configuration file, allowing you to customize various settings. It creates a cashier.php file in your application’s config directory for advanced configuration.
php artisan vendor:publish --tag="cashier-config"
Define Laravel Route to Redirect to Stripe Billing Portal
Source: https://laravel.com/docs/12.x/billing
Implements a Laravel GET route that uses the redirectToBillingPortal method on the authenticated user to send them to the Stripe Customer Billing Portal. Users are returned to the specified dashboard route upon exiting the portal. Requires the auth middleware.
use Illuminate\Http\Request;
Route::get('/billing', function (Request $request) {
return $request->user()->redirectToBillingPortal(route('dashboard'));
})->middleware(['auth'])->name('billing');
HTML Form for Payment Method Update
Source: https://laravel.com/docs/12.x/billing
Define the HTML structure for a form that collects cardholder information and includes a placeholder for Stripe Elements. The update button is crucial as it carries the client secret from the generated Setup Intent as a data attribute, linking the frontend to the backend intent.
<input id="card-holder-name" type="text" />
<!-- Stripe Elements Placeholder -->
<div id="card-element"></div>
<button id="card-button" data-secret="{{ $intent->client_secret }}">Update Payment Method</button>
Define Custom Database Connection for Laravel Eloquent Model
Source: https://laravel.com/docs/12.x/eloquent
This PHP code illustrates how to specify a database connection for an Eloquent model that differs from the application’s default connection. By setting the $connection property on the model, you can ensure that the model interacts with a particular database connection, such as ‘mysql’.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The database connection that should be used by the model.
*
* @var string
*/
protected $connection = 'mysql';
}
Disable Automatic ChromeDriver Start in DuskTestCase
Source: https://laravel.com/docs/12.x/dusk
To use a custom Selenium server or a different browser for testing, comment out or remove the static::startChromeDriver(); call within the prepare method of your tests/DuskTestCase.php file. This prevents Dusk from automatically launching its bundled ChromeDriver.
/**
* Prepare for Dusk test execution.
*
* @beforeClass
*/
public static function prepare(): void
{
// static::startChromeDriver();
}
Define Mass Assignable JSON Column Attributes with $fillable in PHP
Source: https://laravel.com/docs/12.x/eloquent
Explains how to specify mass assignable keys for JSON columns within the $fillable array. For security reasons, Laravel requires explicit definition for nested JSON attributes when performing mass assignment.
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'options->enabled',
];
Configure Laravel Package Discovery in composer.json
Source: https://laravel.com/docs/12.x/packages
This JSON configuration snippet, placed in a package’s composer.json file, enables Laravel’s automatic package discovery. It registers service providers and facade aliases, simplifying installation for users by eliminating manual registration steps.
"extra": {
"laravel": {
"providers": [
"Barryvdh\\Debugbar\\ServiceProvider"
],
"aliases": {
"Debugbar": "Barryvdh\\Debugbar\\Facade"
}
}
},
Debug PHP CLI Application with Xdebug (Shell)
Source: https://laravel.com/docs/12.x/homestead
This command utilizes the xphp shell alias inside your Homestead virtual machine to debug a PHP command-line interface application. Replace /path/to/script with the absolute path to the PHP script you wish to debug. The xphp alias automatically activates Xdebug for the duration of the script’s execution.
xphp /path/to/script
Swap Prices and Invoice Immediately in Laravel
Source: https://laravel.com/docs/12.x/cashier-paddle
Demonstrates how to immediately bill a customer for new or swapped prices on an existing subscription using the swapAndInvoice method. This is useful when instant billing is required.
$user->subscription()->swapAndInvoice(['price_chat', 'price_original' => 2]);
Define Pruning Callback Method for Prunable Models in Laravel
Source: https://laravel.com/docs/12.x/eloquent
This snippet shows how to define a pruning method within a Prunable model. This protected method is called before a model is deleted, allowing for cleanup tasks like removing associated files or resources before the model is permanently removed.
/**
* Prepare the model for pruning.
*/
protected function pruning(): void
{
// ...
}
Retrieve specific type of payment methods (Laravel Cashier)
Source: https://laravel.com/docs/12.x/billing
This PHP example shows how to filter payment methods by a specific type, such as ‘sepa_debit’, when retrieving them from a billable model using Laravel Cashier’s paymentMethods() method. This allows for targeted retrieval of payment options.
$paymentMethods = $user->paymentMethods('sepa_debit');
Execute Commands with Specific PHP Versions in Homestead CLI
Source: https://laravel.com/docs/12.x/homestead
These shell commands demonstrate how to execute PHP-CLI commands using specific PHP versions available within the Homestead virtual machine. This is useful for running artisan commands or custom scripts that require a particular PHP runtime version without changing the global default.
php5.6 artisan list
php7.0 artisan list
php7.1 artisan list
php7.2 artisan list
php7.3 artisan list
php7.4 artisan list
php8.0 artisan list
php8.1 artisan list
php8.2 artisan list
php8.3 artisan list
Create Subscription with Additional Customer and Subscription Details in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP snippet illustrates how to pass additional Stripe customer and subscription options when creating a new subscription. The create method accepts optional second and third arguments for these details, such as email or metadata.
$user->newSubscription('default', 'price_monthly')->create($paymentMethod, [
'email' => $email,
], [
'metadata' => ['note' => 'Some extra information.'],
]);
Install Predis PHP client via Composer
Source: https://laravel.com/docs/12.x/redis
This command installs the predis/predis package, which is a Redis client written entirely in PHP. It is an alternative for Laravel applications that cannot install the PhpRedis PECL extension.
composer require predis/predis
Create New Subscription with Payment Method in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP route example shows how to create a new subscription for a user using Laravel Cashier. It utilizes the newSubscription method with a subscription type and price ID, then calls create with a payment method ID to initiate the subscription and update the database.
use Illuminate\Http\Request;
Route::post('/user/subscribe', function (Request $request) {
$request->user()->newSubscription(
'default', 'price_monthly'
)->create($request->paymentMethodId);
// ...
});
Configure Homestead public/bridged network interface in YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration sets up a public (bridged) network interface for Homestead, allowing the VM to appear as a separate device on the host’s network. It specifies a static IP and the host’s bridge interface to connect the VM directly to the physical network.
networks:
- type: 'public_network'
ip: '192.168.10.20'
bridge: 'en1: Wi-Fi (AirPort)'
Install Algolia PHP SDK for Laravel Scout
Source: https://laravel.com/docs/12.x/scout
Install the Algolia PHP SDK via Composer when using the Algolia driver. This package is a prerequisite for Laravel Scout to interact with Algolia’s search services.
composer require algolia/algoliasearch-client-php
Install Laravel Stream NPM Package for React and Vue
Source: https://laravel.com/docs/12.x/responses
These commands install the necessary @laravel/stream-react or @laravel/stream-vue npm package, which provides the useStream hook for consuming Laravel event streams in your frontend application.
npm install @laravel/stream-react
npm install @laravel/stream-vue
Customize Laravel broadcast queue name using broadcastQueue method
Source: https://laravel.com/docs/12.x/broadcasting
This PHP example provides an alternative method for customizing the queue name for broadcast events. By implementing the broadcastQueue method within the event class, you can dynamically return the desired queue name.
/**
* The name of the queue on which to place the broadcasting job.
*/
public function broadcastQueue(): string
{
return 'default';
}
List All Available Cashier Subscription Query Scopes (PHP)
Source: https://laravel.com/docs/12.x/billing
Provides a comprehensive list of all query scopes available in Laravel Cashier for filtering subscriptions by their various states, such as active, canceled, incomplete, pastDue, onTrial, etc.
Subscription::query()->active();
Subscription::query()->canceled();
Subscription::query()->ended();
Subscription::query()->incomplete();
Subscription::query()->notCanceled();
Subscription::query()->notOnGracePeriod();
Subscription::query()->notOnTrial();
Subscription::query()->onGracePeriod();
Subscription::query()->onTrial();
Subscription::query()->pastDue();
Subscription::query()->recurring();
Increment or Decrement Laravel Cashier Subscription Quantity
Source: https://laravel.com/docs/12.x/billing
This code demonstrates how to increase or decrease the quantity of a user’s default subscription using incrementQuantity and decrementQuantity methods. It shows examples for both single unit changes and changes by a specified amount (e.g., 5 units).
use App\Models\User;
$user = User::find(1);
$user->subscription('default')->incrementQuantity();
// Add five to the subscription's current quantity...
$user->subscription('default')->incrementQuantity(5);
$user->subscription('default')->decrementQuantity();
// Subtract five from the subscription's current quantity...
$user->subscription('default')->decrementQuantity(5);
Navigate to a Specific URI with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This snippet shows how to use the visit method of a Laravel Dusk Browser instance to navigate to a specified URI within your application. It’s the primary method for directing the browser to a particular page.
$browser->visit('/login');
Prevent Silently Discarded Mass Assignment Attributes in PHP
Source: https://laravel.com/docs/12.x/eloquent
Demonstrates how to configure Laravel to throw an exception when an attempt is made to mass-assign an attribute not included in the $fillable array. This method, typically invoked in a service provider’s boot method, is useful for debugging during local development.
use Illuminate\Database\Eloquent\Model;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Model::preventSilentlyDiscardingAttributes($this->app->isLocal());
}
Sync Stripe customer details on model update using Cashier (PHP)
Source: https://laravel.com/docs/12.x/billing
This example shows how to automatically synchronize customer information with Stripe whenever the billable model is updated. An event listener is defined in the booted method to call syncStripeCustomerDetails if the customer has a Stripe ID, ensuring Stripe’s data is current.
use App\Models\User;
use function Illuminate\Events\queueable;
/**
* The "booted" method of the model.
*/
protected static function booted(): void
{
static::updated(queueable(function (User $customer) {
if ($customer->hasStripeId()) {
$customer->syncStripeCustomerDetails();
}
}));
}
Update Vagrant Box for Homestead
Source: https://laravel.com/docs/12.x/homestead
This command updates the underlying Vagrant box that Homestead uses to its latest available version. Keeping the Vagrant box updated ensures your virtual machine base image benefits from the newest bug fixes, security patches, and features.
vagrant box update
Set Currency Locale for Cashier Invoices
Source: https://laravel.com/docs/12.x/cashier-paddle
Specify the currency locale for invoice formatting using the CASHIER_CURRENCY_LOCALE environment variable in your .env file. This leverages PHP’s NumberFormatter class, requiring the ext-intl PHP extension to be installed for locales other than en.
CASHIER_CURRENCY_LOCALE=nl_BE
Extend Subscription Trial Period (PHP)
Source: https://laravel.com/docs/12.x/billing
This PHP code demonstrates how to extend a user’s subscription trial period using Laravel Cashier’s extendTrial method. It shows examples of extending by a fixed number of days from the current time or by adding days to an existing trial end date.
use App\Models\User;
$subscription = User::find(1)->subscription('default');
// End the trial 7 days from now...
$subscription->extendTrial(
now()->addDays(7)
);
// Add an additional 5 days to the trial...
$subscription->extendTrial(
$subscription->trial_ends_at->addDays(5)
);
Store Page Source in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This PHP example demonstrates how to save the HTML source code of the current page to a file during a Laravel Dusk test. The storeSource method takes a filename and stores the page’s HTML in the tests/Browser/source directory, which can aid in debugging rendering issues or content verification.
$browser->storeSource('filename');
Configure Laravel Application for Minio S3 Compatibility
Source: https://laravel.com/docs/12.x/homestead
This snippet provides the .env settings required for a Laravel application to interact with Minio as an Amazon S3-compatible service. It specifies the local endpoint, access keys (homestead/secretkey), and default region (us-east-1) to ensure proper connection to your Minio instance.
AWS_USE_PATH_STYLE_ENDPOINT=true
AWS_ENDPOINT=http://localhost:9600
AWS_ACCESS_KEY_ID=homestead
AWS_SECRET_ACCESS_KEY=secretkey
AWS_DEFAULT_REGION=us-east-1
Configure WorkOS Environment Variables in Laravel
Source: https://laravel.com/docs/12.x/starter-kits
Set the necessary WorkOS environment variables (WORKOS_CLIENT_ID, WORKOS_API_KEY, WORKOS_REDIRECT_URL) in your Laravel application’s .env file. These values should be obtained from your WorkOS dashboard to enable proper authentication and redirection.
WORKOS_CLIENT_ID=your-client-id
WORKOS_API_KEY=your-api-key
WORKOS_REDIRECT_URL="${APP_URL}/authenticate"
Retrieve Aggregate Values with Laravel Eloquent Models
Source: https://laravel.com/docs/12.x/eloquent
Eloquent models can leverage the query builder’s aggregate methods like count, sum, and max to calculate scalar values directly from the database without retrieving full model instances. This is useful for statistical queries.
$count = Flight::where('active', 1)->count();
$max = Flight::where('active', 1)->max('price');
Publish Cashier Database Migrations in Laravel
Source: https://laravel.com/docs/12.x/billing
This Artisan command publishes Cashier’s database migrations to your application’s database/migrations directory. These migrations define the necessary tables and columns for managing Stripe subscriptions and user billing information.
php artisan vendor:publish --tag="cashier-migrations"
Define a Laravel Route to Invoke a Process
Source: https://laravel.com/docs/12.x/processes
This PHP snippet defines a GET route /import that uses Laravel’s Process facade to run a bash import.sh command. It demonstrates a typical scenario where a process needs to be executed within a web request, serving as the basis for subsequent testing examples.
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Route;
Route::get('/import', function () {
Process::run('bash import.sh');
return 'Import complete!';
});
Install Laravel Pulse via Composer
Source: https://laravel.com/docs/12.x/pulse
Installs the Laravel Pulse package using the Composer package manager, integrating it into your Laravel application’s dependencies. This is the foundational step for enabling Pulse.
composer require laravel/pulse
Define Global Environment Variables in Homestead YAML
Source: https://laravel.com/docs/12.x/homestead
This variables block in Homestead.yaml defines global environment variables for the entire Homestead environment. These variables are made available to all PHP-FPM processes and the vagrant user after re-provisioning the machine with vagrant reload --provision.
variables:
- key: APP_ENV
value: local
- key: FOO
value: bar
Laravel Dusk: Retrieving and setting element values
Source: https://laravel.com/docs/12.x/dusk
This snippet demonstrates how to interact with the ‘value’ of an HTML element using Dusk’s value method. It shows how to retrieve an element’s value and how to set a new value, accepting either a CSS or a Dusk selector.
// Retrieve the value...
$value = $browser->value('selector');
// Set the value...
$browser->value('selector', 'value');
Map Eloquent Model Lifecycle Events to Custom Classes
Source: https://laravel.com/docs/12.x/eloquent
Shows how to define the $dispatchesEvents property within an Eloquent model to map specific lifecycle events (e.g., saved, deleted) to custom event classes. This approach provides a structured way to handle model events, with each event class expecting an instance of the affected model via its constructor.
<?php
namespace App\Models;
use App\Events\UserDeleted;
use App\Events\UserSaved;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The event map for the model.
*
* @var array<string, string>
*/
protected $dispatchesEvents = [
'saved' => UserSaved::class,
'deleted' => UserDeleted::class,
];
}
Install Flysystem S3 package for Laravel
Source: https://laravel.com/docs/12.x/filesystem
This Composer command installs the league/flysystem-aws-s3-v3 package, which is required to use the S3 filesystem driver in Laravel. It ensures all necessary dependencies are included for Amazon S3 integration.
composer require league/flysystem-aws-s3-v3 "^3.0" --with-all-dependencies
Retrieve Customer Balance Transactions and Related Invoices
Source: https://laravel.com/docs/12.x/billing
Demonstrates how to retrieve a history of all balance transactions (credits and debits) for a customer. It also shows how to access the amount of each transaction and, if available, the associated invoice, providing a detailed log for review.
// Retrieve all transactions...
$transactions = $user->balanceTransactions();
foreach ($transactions as $transaction) {
// Transaction amount...
$amount = $transaction->amount(); // $2.31
// Retrieve the related invoice when available...
$invoice = $transaction->invoice();
}
Convert HasMany to HasOne Relationship (Laravel PHP)
Source: https://laravel.com/docs/12.x/eloquent-relationships
This PHP example demonstrates how to convert an existing HasMany relationship into a HasOne relationship to retrieve a single related model. It uses the one() method on the orders() HasMany relationship, then applies ofMany to get the largest order by price.
/**
* Get the user's orders.
*/
public function orders(): HasMany
{
return $this->hasMany(Order::class);
}
/**
* Get the user's largest order.
*/
public function largestOrder(): HasOne
{
return $this->orders()->one()->ofMany('price', 'max');
}
Install Flysystem Read-Only package for Laravel
Source: https://laravel.com/docs/12.x/filesystem
This Composer command installs the league/flysystem-read-only package, which enables the read-only configuration option for Laravel filesystem disks. This package is necessary to prevent write operations on a specified disk.
composer require league/flysystem-read-only "^3.0"
Creating a Basic Form with Laravel Prompts in PHP
Source: https://laravel.com/docs/12.x/prompts
This example illustrates how to create a sequence of prompts using the form function in Laravel Prompts. It collects a name, password, and confirmation, returning the responses as a numerically indexed array upon submission.
use function Laravel\Prompts\form;
$responses = form()
->text('What is your name?', required: true)
->password('What is your password?', validate: ['password' => 'min:8'])
->confirm('Do you accept the terms?')
->submit();
Configure Homestead Nginx Site Mapping in YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML snippet demonstrates how to map a custom domain (e.g., homestead.test) to a specific project directory within your Homestead virtual machine. It configures Nginx to serve the specified public folder for the given domain. This is defined in the sites property of the Homestead.yaml file.
sites:
- map: homestead.test
to: /home/vagrant/project1/public
Authenticate User in Laravel Dusk Tests
Source: https://laravel.com/docs/12.x/dusk
This PHP example shows how to use Dusk’s loginAs method to authenticate a user for a browser test, bypassing the login screen. It accepts either a primary key or an authenticatable model instance, allowing the test to proceed directly to protected routes, such as the user’s home page.
use App\Models\User;
use Laravel\Dusk\Browser;
$this->browse(function (Browser $browser) {
$browser->loginAs(User::find(1))
->visit('/home');
});
Manually Control Progress Bar in Laravel
Source: https://laravel.com/docs/12.x/artisan
This example shows how to manually create and control a progress bar for a task in Laravel. It involves initializing the progress bar with a total step count, starting it, advancing it within a loop, and then finishing it after all iterations. This provides granular control over progress updates.
$users = App\Models\User::all();
$bar = $this->output->createProgressBar(count($users));
$bar->start();
foreach ($users as $user) {
$this->performTask($user);
$bar->advance();
}
$bar->finish();
Broadcast Client Events with Echo’s whisper method (JS, React, Vue)
Source: https://laravel.com/docs/12.x/broadcasting
This snippet illustrates how to broadcast client-side events directly to other connected clients using Laravel Echo’s whisper method. This is useful for real-time features like ‘typing’ notifications without involving the Laravel backend. Examples are provided for plain JavaScript, React, and Vue applications.
Echo.private(`chat.${roomId}`).whisper('typing', {
name: this.user.name,
});
import { useEcho } from '@laravel/echo-react';
const { channel } = useEcho(`chat.${roomId}`, ['update'], (e) => {
console.log('Chat event received:', e);
});
channel().whisper('typing', { name: user.name });
<script setup lang="ts">
import { useEcho } from '@laravel/echo-vue';
const { channel } = useEcho(`chat.${roomId}`, ['update'], (e) => {
console.log('Chat event received:', e);
});
channel().whisper('typing', { name: user.name });
</script>
Customize Eloquent Timestamp Column Names in Laravel
Source: https://laravel.com/docs/12.x/eloquent
This PHP snippet shows how to override the default created_at and updated_at column names used by Eloquent. By defining CREATED_AT and UPDATED_AT constants on the model, you can map timestamps to custom column names like creation_date and updated_date.
<?php
class Flight extends Model
{
const CREATED_AT = 'creation_date';
const UPDATED_AT = 'updated_date';
}
Configure root event namespace for Laravel Echo (JavaScript)
Source: https://laravel.com/docs/12.x/broadcasting
This example illustrates how to set a custom root namespace for event classes when initializing Laravel Echo. While Echo defaults to App\Events, passing a namespace configuration option allows specifying an alternative base namespace for event discovery.
window.Echo = new Echo({
broadcaster: 'pusher',
// ...
namespace: 'App.Other.Namespace',
});
POST /oauth/device/code
Source: https://laravel.com/docs/12.x/passport
This endpoint is the initial step for a device to request a device code, user code, verification URI, and polling interval to start the device authorization flow.
## POST /oauth/device/code
### Description
Consuming devices (e.g., smart TVs, IoT devices) make a POST request to this endpoint to obtain the necessary codes and URIs to guide the user through the authorization process on a secondary device.
### Method
POST
### Endpoint
/oauth/device/code
### Parameters
#### Path Parameters
_None_
#### Query Parameters
_None_
#### Request Body
- **client_id** (string) - Required - The client identifier of the device application.
- **scope** (string) - Optional - A space-separated list of scopes the client is requesting (e.g., `user:read orders:create`).
### Request Example
```php
use Illuminate\Support\Facades\Http;
$response = Http::asForm()->post('https://passport-app.test/oauth/device/code', [
'client_id' => 'your-client-id',
'scope' => 'user:read orders:create',
]);
return $response->json();
Response
Success Response (200)
Returns a JSON object containing codes and URIs for the user interaction, along with polling parameters.
Response Example
{
"device_code": "J8L4M5N6P7Q8R9S0T1U2V3W4X5Y6Z7",
"user_code": "ABCD-EFGH",
"verification_uri": "https://passport-app.test/oauth/device/user-code",
"expires_in": 1800,
"interval": 5
}
--------------------------------
### Check Subscription to Specific Paddle Price ID (PHP)
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP example shows how to verify if a user's subscription is tied to a particular Paddle price ID. The `subscribedToPrice()` method allows checking against a specific price and subscription type, ensuring the user is subscribed to the correct plan.
```php
if ($user->subscribedToPrice($monthly = 'pri_123', 'default')) {
// ...
}
Handle Custom Stripe Webhook Events (PHP)
Source: https://laravel.com/docs/12.x/billing
This PHP example demonstrates how to create a listener for Cashier’s WebhookReceived event to handle custom Stripe webhook types, such as invoice.payment_succeeded. It allows for executing specific logic based on the incoming Stripe event payload, extending Cashier’s default webhook handling.
<?php
namespace App\Listeners;
use Laravel\Cashier\Events\WebhookReceived;
class StripeEventListener
{
/**
* Handle received Stripe webhooks.
*/
public function handle(WebhookReceived $event): void
{
if ($event->payload['type'] === 'invoice.payment_succeeded') {
// Handle the incoming event...
}
}
}
Add Price with Specific Quantity to Existing Laravel Cashier Subscription
Source: https://laravel.com/docs/12.x/billing
This example illustrates adding a new billing price (e.g., ‘price_chat’) to an existing user subscription while also specifying a quantity (e.g., 5) for that new price. The quantity is passed as the second argument to the addPrice method.
$user = User::find(1);
$user->subscription('default')->addPrice('price_chat', 5);
Using Laravel Facades for Caching and Routing (PHP)
Source: https://laravel.com/docs/12.x/facades
This example demonstrates how to import and utilize Laravel facades, specifically Cache and Route, to interact with core framework functionalities. Facades provide a static-like interface to classes managed by Laravel’s service container.
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
Route::get('/cache', function () {
return Cache::get('key');
});
Delete Eloquent Models by Primary Key using destroy (PHP)
Source: https://laravel.com/docs/12.x/eloquent
Illustrates using the static destroy method to delete one or more models directly by their primary keys, without explicit retrieval. It supports single keys, multiple arguments, arrays, or collections of keys, and dispatches model events for each deleted model.
Flight::destroy(1);
Flight::destroy(1, 2, 3);
Flight::destroy([1, 2, 3]);
Flight::destroy(collect([1, 2, 3]));
Disable Deferred Functions in Laravel Tests
Source: https://laravel.com/docs/12.x/helpers
This snippet demonstrates how to prevent deferred functions from running during tests. It provides examples for both Pest and PHPUnit test frameworks, and shows how to configure this globally within a base TestCase class’s setUp method.
test('without defer', function () {
$this->withoutDefer();
// ...
});
use TestsTestCase;
class ExampleTest extends TestCase
{
public function test_without_defer(): void
{
$this->withoutDefer();
// ...
}
}
<?php
namespace Tests;
use IlluminateFoundationTestingTestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
protected function setUp(): void
{
parent::setUp();
$this->withoutDefer();
}
}
Configure Laravel Eloquent Model to Use UUID Primary Keys
Source: https://laravel.com/docs/12.x/eloquent
This PHP code demonstrates how to enable UUID primary keys for an Eloquent model using the HasUuids trait. It shows a simple model definition and the creation of a new article, automatically generating a UUID for its ‘id’ field.
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasUuids;
// ...
}
$article = Article::create(['title' => 'Traveling to Europe']);
$article->id; // "8f8e8478-9035-4d23-b9a7-62f4d2612ce5"
Add Custom Bash Aliases in Homestead
Source: https://laravel.com/docs/12.x/homestead
This snippet shows how to add custom Bash aliases to your Homestead virtual machine by modifying the aliases file. After updating this file, you must re-provision the VM using vagrant reload --provision for the new aliases to become available.
alias c='clear'
alias ..='cd ..'
Customize Laravel Model Broadcasting Event Creation
Source: https://laravel.com/docs/12.x/broadcasting
Override the default mechanism for creating broadcastable model events by implementing the newBroadcastableEvent method on your Eloquent model. This method should return an instance of Illuminate\Database\Eloquent\BroadcastableModelEventOccurred, allowing you to configure the event, for example, by preventing it from being broadcast to the current user.
use Illuminate\Database\Eloquent\BroadcastableModelEventOccurred;
/**
* Create a new broadcastable model event for the model.
*/
protected function newBroadcastableEvent(string $event): BroadcastableModelEventOccurred
{
return (new BroadcastableModelEventOccurred(
$this, $event
))->dontBroadcastToCurrentUser();
}
Retrieve and Display Past and Upcoming Subscription Payments (PHP, Blade)
Source: https://laravel.com/docs/12.x/cashier-paddle
These examples demonstrate how to fetch a customer’s lastPayment and nextPayment for recurring subscriptions using Laravel Cashier and then display the upcoming payment details. The PHP code retrieves instances of Laravel\Paddle\Payment, and the Blade snippet formats the output for display.
use App\Models\User;
$user = User::find(1);
$subscription = $user->subscription();
$lastPayment = $subscription->lastPayment();
$nextPayment = $subscription->nextPayment();
Next payment: {{ $nextPayment->amount() }} due on {{ $nextPayment->date()->format('d/m/Y') }}
Start Laravel Octane with Custom FrankenPHP Caddyfile
Source: https://laravel.com/docs/12.x/octane
This shell command demonstrates how to start a Laravel Octane server with FrankenPHP while providing a custom Caddyfile. The --caddyfile option allows users to override FrankenPHP’s default server configurations, enabling advanced routing, custom middleware, or other Caddy directives.
php artisan octane:start --server=frankenphp --caddyfile=/path/to/your/Caddyfile
Implement Prunable Trait for Model Pruning in Laravel
Source: https://laravel.com/docs/12.x/eloquent
This code illustrates how to make an Eloquent model prunable by using the Prunable trait and defining a prunable method. The prunable method returns an Eloquent query builder that identifies models no longer needed, based on specified criteria like created_at date.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
class Flight extends Model
{
use Prunable;
/**
* Get the prunable model query.
*/
public function prunable(): Builder
{
return static::where('created_at', '<=', now()->subMonth());
}
}
Create Subscription with Specific Quantity in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP code demonstrates how to create a new subscription with a predefined quantity for the price. The quantity method is invoked on the subscription builder before calling create to set the desired quantity.
$user->newSubscription('default', 'price_monthly')
->quantity(5)
->create($paymentMethod);
Create Basic Subscription Checkout in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This code demonstrates how to initiate a basic subscription checkout using Laravel Cashier and Stripe. It creates a new subscription for the authenticated user to a specified price (‘price_monthly’) and redirects them to Stripe’s checkout page for payment.
use Illuminate\Http\Request;
Route::get('/subscription-checkout', function (Request $request) {
return $request->user()
->newSubscription('default', 'price_monthly')
->checkout();
});
Install Laravel Precognition Alpine Frontend Helper
Source: https://laravel.com/docs/12.x/precognition
This shell command installs the laravel-precognition-alpine package via NPM. This package provides the necessary frontend helpers to integrate Laravel Precognition with Alpine.js applications for live form validation.
npm install laravel-precognition-alpine
Remove Specific Global Scope from Eloquent Query in Laravel
Source: https://laravel.com/docs/12.x/eloquent
This snippet demonstrates how to remove a single global scope from an Eloquent query. You can specify the scope by its class name or, if it was defined using a closure, by its assigned string name. This is useful for temporarily bypassing specific global constraints.
User::withoutGlobalScope(AncientScope::class)->get();
User::withoutGlobalScope('ancient')->get();
Allow All Attributes for Mass Assignment with Empty $guarded in PHP
Source: https://laravel.com/docs/12.x/eloquent
Shows how to make all model attributes mass assignable by defining the $guarded property as an empty array. If choosing this approach, extreme caution must be exercised to manually validate and hand-craft input arrays passed to Eloquent methods.
/**
* The attributes that aren't mass assignable.
*
* @var array<string>|bool
*/
protected $guarded = [];
Limit Task Execution to Specific Time Ranges (Laravel)
Source: https://laravel.com/docs/12.x/scheduling
These examples illustrate how to limit or exclude a scheduled task’s execution based on a time range. The between method ensures a task runs only within specified start and end times, while unlessBetween prevents it from running during a given period.
Schedule::command('emails:send')
->hourly()
->between('7:00', '22:00');
Schedule::command('emails:send')
->hourly()
->unlessBetween('23:00', '4:00');
Check User’s Specific Subscription Status by Type (PHP)
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP example illustrates how to verify a user’s subscription status for a specific subscription type. By passing the internal type string (e.g., ‘default’) to the subscribed() method, you can differentiate between multiple subscriptions offered by your application.
if ($user->subscribed('default')) {
// ...
}
Configure Homestead public network interface with custom device in YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration defines a public network interface with a specific device (dev) setting for Homestead. It includes a static IP and a host bridge, allowing the user to specify which virtual network device within the VM should be used, overriding the default eth0.
networks:
- type: 'public_network'
ip: '192.168.10.20'
bridge: 'en1: Wi-Fi (AirPort)'
dev: 'enp2s0'
Create Stripe Checkout Session (Laravel)
Source: https://laravel.com/docs/12.x/billing
This Laravel route defines the process for initiating a Stripe Checkout session, allowing a user to subscribe to a specific plan. It configures trial days, enables promotion codes, and specifies success and cancellation URLs for redirection after the checkout process. The user will be redirected to Stripe and then back to the application.
use Illuminate\Http\Request;
Route::get('/subscription-checkout', function (Request $request) {
return $request->user()
->newSubscription('default', 'price_basic_monthly')
->trialDays(5)
->allowPromotionCodes()
->checkout([
'success_url' => route('your-success-route'),
'cancel_url' => route('your-cancel-route'),
]);
});
Get Available Time Until Laravel Rate Limiter Resets
Source: https://laravel.com/docs/12.x/rate-limiting
This PHP example demonstrates how to use RateLimiter::availableIn to determine the number of seconds remaining until more attempts become available after a rate limit has been exceeded. This allows for providing informative feedback to users about when they can retry a rate-limited action.
use Illuminate\Support\Facades\RateLimiter;
if (RateLimiter::tooManyAttempts('send-message:'.$user->id, $perMinute = 5)) {
$seconds = RateLimiter::availableIn('send-message:'.$user->id);
return 'You may try again in '.$seconds.' seconds.';
}
RateLimiter::increment('send-message:'.$user->id);
// Send message...
Lazy load Eloquent models by ID with lazyById in PHP
Source: https://laravel.com/docs/12.x/eloquent
Similar to chunkById, lazyById should be used when updating records during iteration to maintain consistency. It retrieves models based on their ID, ensuring reliable processing of large datasets. The column parameter specifies the ID column for ordered retrieval.
Flight::where('departed', true)
->lazyById(200, column: 'id')
->each->update(['departed' => false]);
Mask String Portions in Laravel
Source: https://laravel.com/docs/12.x/strings
The mask method obfuscates parts of a string with a repeated character, useful for sensitive data like email addresses or phone numbers. Examples show masking from the start, from the end, and a combination of both using positive and negative offsets.
use Illuminate
\Support\Str;
$string = Str::of('taylor@example.com')->mask('*', 3);
// tay***************
$string = Str::of('taylor@example.com')->mask('*', -15, 3);
// tay***@example.com
$string = Str::of('taylor@example.com')->mask('*', 4, -4);
// tayl**********.com
Configure Paddle Sandbox Environment Variable
Source: https://laravel.com/docs/12.x/cashier-paddle
Set the PADDLE_SANDBOX environment variable to true in your .env file to enable the Paddle sandbox for local and staging development, allowing testing without real payments.
PADDLE_SANDBOX=true
Reset Database Using Migrations for Dusk Tests
Source: https://laravel.com/docs/12.x/dusk
To reset your database state before each Dusk test, apply the DatabaseMigrations trait. This trait runs your database migrations, ensuring a clean slate. It’s an alternative to RefreshDatabase for browser tests, as RefreshDatabase does not work across HTTP requests. This example shows implementation for both Pest and PHPUnit.
<?php
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
pest()->use(DatabaseMigrations::class);
//
<?php
namespace Tests\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
class ExampleTest extends DuskTestCase
{
use DatabaseMigrations;
//
}
Implement broadcastOn for Single Private Channel in Laravel Event
Source: https://laravel.com/docs/12.x/broadcasting
This PHP example shows the implementation of the broadcastOn method within an event class. It returns a single PrivateChannel, ensuring that the event is broadcast only to users authorized for that specific channel, typically tied to a resource like an order ID.
use IlluminateBroadcastingChannel;
use IlluminateBroadcastingPrivateChannel;
/**
* Get the channel the event should broadcast on.
*/
public function broadcastOn(): Channel
{
return new PrivateChannel('orders.'.$this->order->id);
}
Install Open Swoole PHP Extension via PECL
Source: https://laravel.com/docs/12.x/octane
This command installs the Open Swoole PHP extension using PECL. Installing Open Swoole is necessary to leverage the Open Swoole application server with Laravel Octane, providing functionalities such as concurrent tasks, ticks, and intervals similar to Swoole.
pecl install openswoole
Define Custom Table Name in Laravel Eloquent Model
Source: https://laravel.com/docs/12.x/eloquent
Eloquent models by default use the ‘snake case’, plural name of the class as the table name. This snippet demonstrates how to explicitly specify a different table name for an Eloquent model by defining the protected ‘$table’ property.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'my_flights';
}
Configure Trial Period for Stripe Subscription Checkout in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This example shows how to add a trial period to a new subscription initiated via Stripe Checkout using Laravel Cashier. The trialDays() method sets the duration of the trial, with a minimum requirement of 48 hours for Stripe Checkout compatibility.
$checkout = Auth::user()->newSubscription('default', 'price_monthly')
->trialDays(3)
->checkout();
Implement Channel Authorization Logic in Laravel Class
Source: https://laravel.com/docs/12.x/broadcasting
This PHP class defines the join method within a broadcast channel class, which contains the authorization logic for the channel. It demonstrates how to authenticate a user’s access to a specific channel, leveraging model binding for the Order object to simplify authorization checks.
<?php
namespace App\Broadcasting;
use App\Models\Order;
use App\Models\User;
class OrderChannel
{
/**
* Create a new channel instance.
*/
public function __construct() {}
/**
* Authenticate the user's access to the channel.
*/
public function join(User $user, Order $order): array|bool
{
return $user->id === $order->user_id;
}
}
Check for specific type of payment method presence (Laravel Cashier)
Source: https://laravel.com/docs/12.x/billing
This PHP example demonstrates how to check if a billable model has a payment method of a specific type (e.g., ‘sepa_debit’) using Laravel Cashier’s hasPaymentMethod() method. This allows for type-specific payment option verification.
if ($user->hasPaymentMethod('sepa_debit')) {
// ...
}
Test Laravel Console Command with Mocked Search Input
Source: https://laravel.com/docs/12.x/console-tests
This example demonstrates testing a console command that utilizes Laravel Prompts’ search or multisearch functions. The expectsSearch assertion mocks the user’s input during the search, the available answers, and the final selected answer, ensuring the command behaves as expected without actual user interaction. This example shows both Pest and PHPUnit syntax.
test('console command', function () {
$this->artisan('example')
->expectsSearch('What is your name?', search: 'Tay', answers: [
'Taylor Otwell',
'Taylor Swift',
'Darian Taylor'
], answer: 'Taylor Otwell')
->assertExitCode(0);
});
/**
* Test a console command.
*/
public function test_console_command(): void
{
$this->artisan('example')
->expectsSearch('What is your name?', search: 'Tay', answers: [
'Taylor Otwell',
'Taylor Swift',
'Darian Taylor'
], answer: 'Taylor Otwell')
->assertExitCode(0);
}
GET /photos/create
Source: https://laravel.com/docs/12.x/controllers
Display the form for creating a new photo resource. This endpoint typically returns an HTML view.
## GET /photos/create
### Description
Display the form for creating a new photo resource.
### Method
GET
### Endpoint
/photos/create
### Parameters
#### Path Parameters
_None_
#### Query Parameters
_None_
#### Request Body
_None_
### Request Example
{}
### Response
#### Success Response (200)
- **html_form** (string) - HTML content for the resource creation form.
#### Response Example
"<!DOCTYPE html>\n<html>\n <head>\n <title>Create Photo</title>\n </head>\n <body>\n <h1>Create New Photo</h1>\n <form action=\"/photos\" method=\"POST\">\n <label for=\"title\">Title:</label>\n <input type=\"text\" id=\"title\" name=\"title\"><br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>"
Injecting Service Dependencies into a Laravel Controller
Source: https://laravel.com/docs/12.x/container
This PHP example demonstrates dependency injection in a Laravel controller’s constructor. The AppleMusic service is type-hinted and automatically injected into PodcastController, allowing for easy mocking during testing and managing external data sources.
<?php
namespace App\Http\Controllers;
use App\Services\AppleMusic;
use Illuminate\View\View;
class PodcastController extends Controller
{
/**
* Create a new controller instance.
*/
public function __construct(
protected AppleMusic $apple,
) {}
/**
* Show information about the given podcast.
*/
public function show(string $id): View
{
return view('podcasts.show', [
'podcast' => $this->apple->findPodcast($id)
]);
}
}
Orchestrate Concurrent Process Pool in Laravel PHP
Source: https://laravel.com/docs/12.x/processes
This PHP example illustrates how to create and manage a pool of concurrent asynchronous processes using Laravel’s Process::pool() method. It defines multiple commands with optional paths, starts the pool with a real-time output callback, and then waits for all processes to complete using wait() to collect their results.
use Illuminate\Process\Pool;
use Illuminate\Support\Facades\Process;
$pool = Process::pool(function (Pool $pool) {
$pool->path(__DIR__)->command('bash import-1.sh');
$pool->path(__DIR__)->command('bash import-2.sh');
$pool->path(__DIR__)->command('bash import-3.sh');
})->start(function (string $type, string $output, int $key) {
// ...
});
while ($pool->running()->isNotEmpty()) {
// ...
}
$results = $pool->wait();
Laravel PHP: Retrieve Command Options (Specific and All)
Source: https://laravel.com/docs/12.x/artisan
This PHP example shows how to retrieve both a specific option and all options within a Laravel console command. The option method fetches a named option, while the options method returns all available options as an array.
// Retrieve a specific option...
$queueName = $this->option('queue');
// Retrieve all options as an array...
$options = $this->options();
Set Laravel Cashier Generic Trial End Date on User Creation
Source: https://laravel.com/docs/12.x/cashier-paddle
This code demonstrates how to create a new user and immediately set a generic trial end date using Laravel Cashier’s createAsCustomer method. This allows users to start a trial without providing payment information upfront. The trial duration is defined by the trial_ends_at property.
use App\Models\User;
$user = User::create([
// ...
]);
$user->createAsCustomer([
'trial_ends_at' => now()->addDays(10)
]);
Get User Input with Text Prompt (PHP)
Source: https://laravel.com/docs/12.x/prompts
The text function prompts the user for a single line of input. These examples demonstrate basic usage, adding placeholder text, default values, hints, and various validation options including simple required checks, custom closure-based validation, and leveraging Laravel’s validator rules.
use function Laravel\Prompts\text;
$name = text('What is your name?');
$name = text(
label: 'What is your name?',
placeholder: 'E.g. Taylor Otwell',
default: $user?->name,
hint: 'This will be displayed on your profile.'
);
$name = text(
label: 'What is your name?',
required: true
);
$name = text(
label: 'What is your name?',
required: 'Your name is required.'
);
$name = text(
label: 'What is your name?',
validate: fn (string $value) => match (true) {
strlen($value) < 3 => 'The name must be at least 3 characters.',
strlen($value) > 255 => 'The name must not exceed 255 characters.',
default => null
}
);
$name = text(
label: 'What is your name?',
validate: ['name' => 'required|max:255|unique:users']
);
Preview subscription invoice with multiple new prices in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
Enables previewing an invoice with several new price changes for a subscription by passing an array of price IDs to the previewInvoice method. This helps visualize complex billing adjustments.
$invoice = $user->subscription('default')->previewInvoice(['price_yearly', 'price_metered']);
Execute closure if Laravel Fluent String starts with substring with whenStartsWith (PHP)
Source: https://laravel.com/docs/12.x/strings
The whenStartsWith method invokes a closure if the string starts with the given sub-string. The closure receives the fluent string instance.
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('disney world')->whenStartsWith('disney', function (Stringable $string) {
return $string->title();
});
// 'Disney World'
Select Column with Subquery for Last Related Record (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This PHP snippet demonstrates using an Eloquent subquery within the addSelect method to retrieve a specific piece of information from a related table. It fetches the name of the most recently arrived flight for each destination in a single database query, optimizing data retrieval.
use App\Models\Destination;
use App\Models\Flight;
return Destination::addSelect(['last_flight' => Flight::select('name')
->whereColumn('destination_id', 'destinations.id')
->orderByDesc('arrived_at')
->limit(1)
])->get();
Broadcast Anonymous Event Immediately (PHP)
Source: https://laravel.com/docs/12.x/broadcasting
By default, anonymous events are queued. To broadcast an event synchronously and immediately, bypassing the queue, use the ‘sendNow()’ method instead of ‘send()’.
Broadcast::on('orders.'.$order->id)->sendNow();
Execute JavaScript in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This PHP example illustrates how to execute arbitrary JavaScript code within the browser during a Laravel Dusk test using the script method. It can be used to perform client-side actions, such as scrolling the page, or to retrieve values from the browser’s JavaScript environment.
$browser->script('document.documentElement.scrollTop = 0');
$browser->script([
'document.body.scrollTop = 0',
'document.documentElement.scrollTop = 0',
]);
$output = $browser->script('return window.location.pathname');
Listen for Multiple Events on Private Channel with Laravel Echo (JavaScript)
Source: https://laravel.com/docs/12.x/broadcasting
For private channels, use ‘Echo.private()’ instead of ‘Echo.channel()’. You can chain multiple ‘.listen()’ calls to subscribe to several distinct events on the same private channel instance.
Echo.private(`orders.${this.order.id}`).listen(/* ... */).listen(/* ... */).listen(/* ... */);
Join Laravel Presence Channel and Handle Events in JavaScript
Source: https://laravel.com/docs/12.x/broadcasting
This JavaScript snippet demonstrates how to join a Laravel Echo presence channel using Echo.join(). It subscribes to here, joining, leaving, and error events to manage and react to the presence of users within the channel, providing real-time updates on who is currently in the channel.
Echo.join(`chat.${roomId}`)
.here((users) => {
// ...
})
.joining((user) => {
console.log(user.name);
})
.leaving((user) => {
console.log(user.name);
})
.error((error) => {
console.error(error);
});
Test file uploads and storage interactions with Laravel Storage fake
Source: https://laravel.com/docs/12.x/filesystem
These examples demonstrate how to use Storage::fake and UploadedFile::fake to test file uploads and storage interactions without hitting the actual filesystem. It includes assertions for checking file existence, absence, count, and directory emptiness using both Pest and PHPUnit testing frameworks.
<?php
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
test('albums can be uploaded', function () {
Storage::fake('photos');
$response = $this->json('POST', '/photos', [
UploadedFile::fake()->image('photo1.jpg'),
UploadedFile::fake()->image('photo2.jpg')
]);
// Assert one or more files were stored...
Storage::disk('photos')->assertExists('photo1.jpg');
Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']);
// Assert one or more files were not stored...
Storage::disk('photos')->assertMissing('missing.jpg');
Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']);
// Assert that the number of files in a given directory matches the expected count...
Storage::disk('photos')->assertCount('/wallpapers', 2);
// Assert that a given directory is empty...
Storage::disk('photos')->assertDirectoryEmpty('/wallpapers');
});
<?php
namespace Tests\Feature;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_albums_can_be_uploaded(): void
{
Storage::fake('photos');
$response = $this->json('POST', '/photos', [
UploadedFile::fake()->image('photo1.jpg'),
UploadedFile::fake()->image('photo2.jpg')
]);
// Assert one or more files were stored...
Storage::disk('photos')->assertExists('photo1.jpg');
Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']);
// Assert one or more files were not stored...
Storage::disk('photos')->assertMissing('missing.jpg');
Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']);
// Assert that the number of files in a given directory matches the expected count...
Storage::disk('photos')->assertCount('/wallpapers', 2);
// Assert that a given directory is empty...
Storage::disk('photos')->assertDirectoryEmpty('/wallpapers');
}
}
Start a Laravel Queue Listener for Code Reloads (Shell)
Source: https://laravel.com/docs/12.x/queues
The php artisan queue:listen command starts a queue listener that automatically reloads code changes and resets application state between jobs. While convenient for development as it eliminates manual restarts, it is significantly less efficient than queue:work for production environments.
php artisan queue:listen
Dispatch Initial Laravel Job Batch with Loaders
Source: https://laravel.com/docs/12.x/queues
This PHP code demonstrates how to dispatch an initial batch of jobs using Bus::batch(). It includes loader jobs that will subsequently add more jobs to the batch, defines a then callback for successful completion, and names the batch.
$batch = Bus::batch([
new LoadImportBatch,
new LoadImportBatch,
new LoadImportBatch,
])->then(function (Batch $batch) {
// All jobs completed successfully...
})->name('Import Contacts')->dispatch();
Listen to custom Laravel broadcast event name in JavaScript
Source: https://laravel.com/docs/12.x/broadcasting
This JavaScript example shows how to listen for a Laravel broadcast event with a custom name using Echo. By prefixing the custom event name with a leading dot (‘.’), Echo is instructed not to prepend the application’s namespace, ensuring correct event reception.
.listen('.server.created', function (e) {
// ...
});
Resize Browser Window Dimensions with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This snippet shows how to use the resize method to programmatically adjust the width and height of the browser window. This is useful for testing responsive designs or ensuring layouts appear correctly at specific screen resolutions.
$browser->resize(1920, 1080);
Implement MassPrunable Trait for Efficient Model Pruning in Laravel
Source: https://laravel.com/docs/12.x/eloquent
This code demonstrates how to use the MassPrunable trait for highly efficient model pruning in Laravel. Unlike Prunable, this trait performs mass deletions directly in the database, bypassing individual model events and the pruning method for improved performance on large datasets.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\MassPrunable;
class Flight extends Model
{
use MassPrunable;
/**
* Get the prunable model query.
*/
public function prunable(): Builder
{
return static::where('created_at', '<=', now()->subMonth());
}
}
Define Laravel Broadcast Channel Authorization Callback
Source: https://laravel.com/docs/12.x/broadcasting
This PHP example illustrates how to define an authorization callback for a private broadcast channel in Laravel. Using Broadcast::channel in routes/channels.php, you can specify a closure that receives the authenticated user and channel parameters to determine if the user is authorized to listen to the channel. This ensures secure access to private real-time data.
use AppModelsUser;
Broadcast::channel('orders.{orderId}', function (User $user, int $orderId) {
return $user->id === Order::findOrNew($orderId)->user_id;
});
Access StripeClient Instance in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP snippet shows how to obtain the Stripe\StripeClient instance directly through the Cashier::stripe() method. This allows for direct interaction with the Stripe SDK to perform operations like fetching all prices from the Stripe account.
use Laravel\Cashier\Cashier;
$prices = Cashier::stripe()->prices->all();
Check Specific Product or Price Subscription Status (Blade)
Source: https://laravel.com/docs/12.x/billing
These Blade examples illustrate how to check for more granular subscription statuses. The subscribedToProduct() method verifies if a user is subscribed to any plan under a given product, while subscribedToPrice() checks for a subscription to a specific price identifier. This allows for fine-grained control over content access based on specific subscription tiers.
@if ($user->subscribedToProduct('pro_basic'))
<p>You are subscribed to our Basic product.</p>
@endif
@if ($user->subscribedToPrice('price_basic_monthly'))
<p>You are subscribed to our monthly Basic plan.</p>
@endif
Integrate Existing Axios Instance with Laravel Precognition Vue
Source: https://laravel.com/docs/12.x/precognition
This JavaScript example demonstrates how to configure laravel-precognition-vue to use an already existing and configured Axios instance. It sets up a global Axios instance with a common authorization header and then instructs Precognition to use this instance with client.use(window.axios). This is beneficial when your application has a unified Axios setup.
import Axios from 'axios';
import { client } from 'laravel-precognition-vue';
window.axios = Axios.create();
window.axios.defaults.headers.common['Authorization'] = authToken;
client.use(window.axios);
Configure Homestead public network interface with DHCP in YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration enables a public (bridged) network interface for Homestead using DHCP. By omitting the ip option, the virtual machine automatically obtains an IP address from the network via the specified host bridge.
networks:
- type: 'public_network'
bridge: 'en1: Wi-Fi (AirPort)'
Register a View Creator (Laravel PHP)
Source: https://laravel.com/docs/12.x/views
This PHP snippet illustrates how to register a view creator using View::creator. View creators are similar to composers but execute immediately after the view is instantiated, rather than waiting until render time. This makes them suitable for initial data binding or setup that needs to occur at the earliest possible stage.
use App\View\Creators\ProfileCreator;
use Illuminate\Support\Facades\View;
View::creator('profile', ProfileCreator::class);
Determine if a Valet driver serves a request (PHP)
Source: https://laravel.com/docs/12.x/valet
The serves method determines if a custom Valet driver should handle an incoming request. It typically checks for specific file or directory structures within the provided $sitePath to identify the application type. This example demonstrates how to check for a WordPress installation by looking for the wp-admin directory.
/**
* Determine if the driver serves the request.
*/
public function serves(string $sitePath, string $siteName, string $uri): bool
{
return is_dir($sitePath.'/wp-admin');
}
Access and store data in Laravel session cache
Source: https://laravel.com/docs/12.x/session
Provides examples of how to retrieve and store data in the session-scoped cache using get() and put() methods on the session’s cache instance. This cache is isolated per user session, ideal for temporary, user-specific data that persists across requests.
$discount = $request->session()->cache()->get('discount');
$request->session()->cache()->put(
'discount', 10, now()->addMinutes(5)
);
Implement Custom Laravel Eloquent Cast for JSON
Source: https://laravel.com/docs/12.x/eloquent-mutators
Provides an example of a custom cast class AsJson that implements the CastsAttributes interface. It defines get to decode JSON from the database into an array and set to encode values into JSON for storage, handling the transformation between model attribute and database column.
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
class AsJson implements CastsAttributes
{
/**
* Cast the given value.
*
* @param array<string, mixed> $attributes
* @return array<string, mixed>
*/
public function get(
Model $model,
string $key,
mixed $value,
array $attributes,
): array {
return json_decode($value, true);
}
/**
* Prepare the given value for storage.
*
* @param array<string, mixed> $attributes
*/
public function set(
Model $model,
string $key,
mixed $value,
array $attributes,
): string {
return json_encode($value);
}
}
Create On-Demand Filesystem Disk in Laravel
Source: https://laravel.com/docs/12.x/filesystem
This code illustrates how to dynamically create a filesystem disk at runtime using the Storage facade’s ‘build’ method. It allows you to use a custom configuration without defining it in the ‘filesystems’ configuration file, useful for temporary or unique storage needs.
use Illuminate\Support\Facades\Storage;
$disk = Storage::build([
'driver' => 'local',
'root' => '/path/to/root'
]);
$disk->put('image.jpg', $content);
Define Laravel Envoy Story with Multiple Tasks (Blade)
Source: https://laravel.com/docs/12.x/envoy
This Blade example shows how to define an Envoy ‘story’ named ‘deploy’ that groups multiple tasks, ‘update-code’ and ‘install-dependencies’. It also defines the individual tasks, demonstrating common deployment steps like Git pull and Composer install. Stories simplify complex deployment workflows by allowing a single invocation to run a sequence of tasks.
@servers(['web' => ['user@192.168.1.1']])
@story('deploy')
update-code
install-dependencies
@endstory
@task('update-code')
cd /home/user/example.com
git pull origin master
@endtask
@task('install-dependencies')
cd /home/user/example.com
composer install
@endtask
Retrieve Paddle price previews for a specific country in PHP
Source: https://laravel.com/docs/12.x/cashier-paddle
This example shows how to retrieve price previews for specific price IDs, overriding the default IP-based currency detection. It allows specifying a country_code and postal_code to ensure prices are calculated for a particular region. The previewPrices method accepts an optional array for address details.
use Laravel\Paddle\Cashier;
$prices = Cashier::previewPrices(['pri_123', 'pri_456'], ['address' => [
'country_code' => 'BE',
'postal_code' => '1234',
]]);
Broadcast Laravel events synchronously using ShouldBroadcastNow interface
Source: https://laravel.com/docs/12.x/broadcasting
This PHP code demonstrates how to make a Laravel event broadcast synchronously, meaning it will be processed immediately rather than being pushed to a queue. This is achieved by implementing the Illuminate\Contracts\Broadcasting\ShouldBroadcastNow interface instead of ShouldBroadcast.
<?php
namespace AppEvents;
use IlluminateContractsBroadcastingShouldBroadcastNow;
class OrderShipmentStatusUpdated implements ShouldBroadcastNow
{
// ...
}
Install Laravel Tinker via Composer
Source: https://laravel.com/docs/12.x/artisan
This Composer command installs the Laravel Tinker package, a powerful REPL for Laravel. It’s used to add Tinker to your project if it was previously removed, enabling interactive command-line access to your application.
composer require laravel/tinker
Authenticate User and Grant Abilities for Testing with Sanctum in PHP
Source: https://laravel.com/docs/12.x/sanctum
These examples demonstrate how to use Sanctum::actingAs during testing to authenticate a user and specify the abilities granted to their token. The first example uses Pest for testing, while the second uses PHPUnit, both showing how to simulate an authenticated user with specific permissions.
use App\Models\User;
use Laravel\Sanctum\Sanctum;
test('task list can be retrieved', function () {
Sanctum::actingAs(
User::factory()->create(),
['view-tasks']
);
$response = $this->get('/api/task');
$response->assertOk();
});
use App\Models\User;
use Laravel\Sanctum\Sanctum;
public function test_task_list_can_be_retrieved(): void
{
Sanctum::actingAs(
User::factory()->create(),
['view-tasks']
);
$response = $this->get('/api/task');
$response->assertOk();
}
Connect to Presence Channels using useEchoPresence (React & Vue)
Source: https://laravel.com/docs/12.x/broadcasting
These snippets illustrate how to connect to a Laravel Echo presence channel using the useEchoPresence hook/composable in both React and Vue. They listen for a ‘PostPublished’ event on the ‘posts’ channel, logging the received event data to the console.
import { useEchoPresence } from '@laravel/echo-react';
useEchoPresence('posts', 'PostPublished', (e) => {
console.log(e.post);
});
<script setup lang="ts">
import { useEchoPresence } from '@laravel/echo-vue';
useEchoPresence('posts', 'PostPublished', (e) => {
console.log(e.post);
});
</script>
Finalize RoadRunner Setup and Rebuild Laravel Sail Images
Source: https://laravel.com/docs/12.x/octane
These commands complete the RoadRunner setup within Laravel Sail. The chmod command makes the downloaded RoadRunner binary executable, and ./vendor/bin/sail build --no-cache rebuilds the Sail Docker images to apply all changes, ensuring the RoadRunner server is ready to run.
chmod +x ./rr
./vendor/bin/sail build --no-cache
Manually control Echo channel listeners with useEcho return functions (React/Vue)
Source: https://laravel.com/docs/12.x/broadcasting
This snippet demonstrates how to access the manual control functions (e.g., leaveChannel, stopListening, listen) returned by the useEcho hook. These functions allow programmatic control over the channel’s listening state, providing flexibility beyond automatic component lifecycle management.
import { useEcho } from '@laravel/echo-react';
const { leaveChannel, leave, stopListening, listen } = useEcho(`orders.${orderId}`, 'OrderShipmentStatusUpdated', (e) => {
console.log(e.order);
});
// Stop listening without leaving channel...
stopListening();
// Start listening again...
listen();
// Leave channel...
leaveChannel();
// Leave a channel and also its associated private and presence channels...
leave();
<script setup lang="ts">
import { useEcho } from '@laravel/echo-vue';
const { leaveChannel, leave, stopListening, listen } = useEcho(`orders.${orderId}`, 'OrderShipmentStatusUpdated', (e) => {
console.log(e.order);
});
// Stop listening without leaving channel...
stopListening();
// Start listening again...
listen();
// Leave channel...
leaveChannel();
// Leave a channel and also its associated private and presence channels...
leave();
</script>
Install Laravel MongoDB Package via Composer
Source: https://laravel.com/docs/12.x/mongodb
This command uses Composer to install the official mongodb/laravel-mongodb package, which provides a richer integration with Laravel’s Eloquent and other features. This package depends on the mongodb PHP extension being installed and enabled.
composer require mongodb/laravel-mongodb
Define PHP Setup Block for Envoy Tasks
Source: https://laravel.com/docs/12.x/envoy
Allows arbitrary PHP code to be executed before any Envoy tasks run. This is useful for initializing variables, setting up environment details, or performing pre-task logic within the Envoy environment.
@setup
$now = new DateTime;
@endsetup
Process Eloquent records by ID in chunks with chunkById in PHP
Source: https://laravel.com/docs/12.x/eloquent
When updating records while iterating, chunkById should be used instead of chunk to avoid inconsistent results. This method internally retrieves models with an id greater than the last processed ID, ensuring reliable iteration even with concurrent updates. The column parameter specifies the ID column.
Flight::where('departed', true)
->chunkById(200, function (Collection $flights) {
$flights->each->update(['departed' => false]);
}, column: 'id');
Create a new database table using Laravel’s Schema facade
Source: https://laravel.com/docs/12.x/migrations
Provides an example of how to define and create a new database table in Laravel using the ‘Schema::create’ method. It takes the table name and a closure with a Blueprint object to specify columns like ‘id’, ‘string’, and ‘timestamps’.
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->timestamps();
});
Disable VirtualBox natdnshostresolver in Homestead YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration for Homestead overrides the default natdnshostresolver setting for VirtualBox to ‘off’. This prevents Homestead from using the host operating system’s DNS settings, allowing for custom or internal DNS configurations within the VM.
provider: virtualbox
natdnshostresolver: 'off'
Generate Stripe billing portal URL without redirection using Cashier (PHP)
Source: https://laravel.com/docs/12.x/billing
This snippet demonstrates how to obtain the URL for the Stripe billing portal without immediately performing an HTTP redirect. The billingPortalUrl method is used to get the URL, which can then be embedded in emails, links, or used in other non-redirect scenarios.
$url = $request->user()->billingPortalUrl(route('billing'));
Manually starting a database transaction in Laravel
Source: https://laravel.com/docs/12.x/database
This code illustrates how to manually begin a database transaction using DB::beginTransaction(). This approach provides explicit control over when to commit or roll back the transaction, suitable for more complex scenarios where automatic handling is not sufficient.
use Illuminate\Support\Facades\DB;
DB::beginTransaction();
Navigate to a Named Route with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This snippet demonstrates using the visitRoute method to navigate to a named route defined in your Laravel application. It accepts the route name and an optional array of parameters, providing a robust way to link to specific parts of your application.
$browser->visitRoute($routeName, $parameters);
Test Basic Successful HTTP Response (Pest/PHPUnit)
Source: https://laravel.com/docs/12.x/http-tests
This snippet demonstrates how to write a basic HTTP test in Laravel using either Pest or PHPUnit to verify that a GET request to the root URL returns a 200 OK status. It showcases the get() method for making requests and assertStatus() for asserting the HTTP status code.
<?php
test('the application returns a successful response', function () {
$response = $this->get('/');
$response->assertStatus(200);
});
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_the_application_returns_a_successful_response(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
Dispatch a Basic PHP Closure as a Queue Job
Source: https://laravel.com/docs/12.x/queues
This code example shows how to dispatch a PHP closure directly to the queue instead of a dedicated job class. This approach is ideal for quick, simple tasks that need to run asynchronously and ensures the closure’s content is cryptographically signed for security.
use App\Models\Podcast;
$podcast = Podcast::find(1);
dispatch(function () use ($podcast) {
$podcast->publish();
});
Iterate Eloquent Models with Cursor for Memory Efficiency (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This PHP snippet demonstrates using the cursor method on an Eloquent query to iterate over a large number of records. It significantly reduces memory consumption by loading only one model into memory at a time, leveraging PHP generators. This is useful for processing thousands of records without running out of memory.
use App\Models\Flight;
foreach (Flight::where('destination', 'Zurich')->cursor() as $flight) {
// ...
}
Query Subscriptions by State using Scopes (PHP)
Source: https://laravel.com/docs/12.x/billing
Shows how to retrieve subscriptions based on their active or canceled status using Cashier’s query scopes. This allows for easy filtering of subscriptions directly from the database.
// Get all active subscriptions...
$subscriptions = Subscription::query()->active()->get();
// Get all of the canceled subscriptions for a user...
$subscriptions = $user->subscriptions()->canceled()->get();
Configure Vite for Manual HTTPS with Trusted Certificates
Source: https://laravel.com/docs/12.x/vite
When using a web server other than Laravel Herd or Valet, this configuration allows you to manually set up HTTPS for Vite by providing paths to trusted SSL key and certificate files. This ensures a secure connection to the Vite development server. The fs module is used to read the certificate files.
// ...
import fs from 'fs';
const host = 'my-app.test';
export default defineConfig({
// ...
server: {
host,
hmr: { host },
https: {
key: fs.readFileSync(`/path/to/${host}.key`),
cert: fs.readFileSync(`/path/to/${host}.crt`),
},
},
});
Update Local Hosts File for Homestead Sites
Source: https://laravel.com/docs/12.x/homestead
If Vagrant does not automatically manage your local hosts file, you must manually add new Homestead site mappings. This associates the Homestead VM’s IP address with the site domains, allowing access from your host machine. The file location varies by operating system.
192.168.56.56 homestead.test
192.168.56.56 another.test
Publish Laravel MCP AI Routes File
Source: https://laravel.com/docs/12.x/mcp
After installation, execute this Artisan command to publish the routes/ai.php file. This file is crucial for defining and registering your Model Context Protocol (MCP) servers.
php artisan vendor:publish --tag=ai-routes
Configure Homestead private network interface in YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration defines a private network interface for the Homestead virtual machine, assigning a static IP address. It facilitates internal communication within the virtual environment without exposing the VM directly to the host’s public network.
networks:
- type: 'private_network'
ip: '192.168.10.20'
Set PHP Version for Homestead Site in YAML
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration sets a specific PHP version for a given Homestead site. By adding the php directive with a version string, the Nginx site will be configured to use that PHP-FPM version, allowing multiple PHP versions to coexist on the same virtual machine.
sites:
- map: homestead.test
to: /home/vagrant/project1/public
php: '7.1'
Add Custom Metadata to Laravel Cashier Paddle Subscription Checkout (PHP)
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP example shows how to attach custom metadata to a Paddle subscription checkout session. The customData method allows passing an associative array of key-value pairs, which can be useful for tracking additional information about the subscription.
$checkout = $request->user()->subscribe($premium = 'pri_123', 'default')
->customData(['key' => 'value'])
->returnTo(route('home'));
Refund Specific Line Items in Paddle Transaction (PHP)
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP example demonstrates how to partially or fully refund specific line items within a Paddle transaction for a given user. It utilizes the refund method on a Cashier\Paddle\Transaction model, accepting a reason and an associative array of price IDs with optional amounts for partial refunds.
use App\Models\User;
$user = User::find(1);
$transaction = $user->transactions()->first();
$response = $transaction->refund('Accidental charge', [
'pri_123', // Fully refund this price...
'pri_456' => 200, // Only partially refund this price...
]);
List All Configured Valet Proxies (Shell)
Source: https://laravel.com/docs/12.x/valet
This shell command displays a comprehensive list of all Laravel Valet site configurations that are currently set up as proxies. It’s useful for quickly reviewing which local domains are redirecting their traffic to other services running on your machine.
valet proxies
Install Laravel MCP Package
Source: https://laravel.com/docs/12.x/mcp
This command uses Composer to install the Laravel MCP package into your project. It adds the necessary dependencies to enable AI client integration with your Laravel application.
composer require laravel/mcp
Install AWS SDK for DynamoDB Cache Driver (Shell)
Source: https://laravel.com/docs/12.x/cache
This command installs the AWS SDK for PHP via Composer, which is a necessary dependency for your Laravel application to communicate with DynamoDB when using it as a cache driver.
composer require aws/aws-sdk-php
Retrieve Laravel Cashier Trial End Date
Source: https://laravel.com/docs/12.x/cashier-paddle
This code demonstrates how to get the trial ending date for a user’s subscription using the trialEndsAt() method. It returns a Carbon date instance if the user is on trial, or null otherwise. An optional subscription type can be passed to check a specific subscription.
if ($user->onTrial('default')) {
$trialEndsAt = $user->trialEndsAt();
}
Configure Laravel Vite Plugin Build Settings
Source: https://laravel.com/docs/12.x/vite
These snippets demonstrate how to customize various build settings for the Laravel Vite plugin. The Blade directive allows setting the hot file, build directory, manifest filename, entry points, and a custom asset path generator, while the JavaScript configuration in vite.config.js provides the corresponding setup for Vite itself.
<!doctype html>
<head>
{{-- ... --}}
{{
Vite::useHotFile(storage_path('vite.hot')) // Customize the "hot" file...
->useBuildDirectory('bundle') // Customize the build directory...
->useManifestFilename('assets.json') // Customize the manifest filename...
->withEntryPoints(['resources/js/app.js']) // Specify the entry points...
->createAssetPathsUsing(function (string $path, ?bool $secure) { // Customize the backend path generation for built assets...
return "https://cdn.example.com/{$path}";
})
}}
</head>
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
hotFile: 'storage/vite.hot', // Customize the "hot" file...
buildDirectory: 'bundle', // Customize the build directory...
input: ['resources/js/app.js'], // Specify the entry points...
}),
],
build: {
manifest: 'assets.json', // Customize the manifest filename...
},
});
Define Laravel Nested Resource Route and Example URI
Source: https://laravel.com/docs/12.x/controllers
Declares a nested resource route using ‘dot’ notation, associating a child resource (e.g., comments) with a parent resource (e.g., photos). The example URI illustrates how the parent and child resource identifiers are incorporated into the URL.
use App\Http\Controllers\PhotoCommentController;
Route::resource('photos.comments', PhotoCommentController::class);
/photos/{photo}/comments/{comment}
Broadcast Laravel Event to All Except Current User
Source: https://laravel.com/docs/12.x/broadcasting
This PHP example shows how to use the toOthers method with the broadcast helper to send an event to all subscribers of a channel except the originating user. This is particularly useful for real-time applications to prevent duplicate updates in the UI when a user’s action already updates their local state.
use App\Events\OrderShipmentStatusUpdated;
broadcast(new OrderShipmentStatusUpdated($update))->toOthers();
Prevent Laravel Eloquent From Silently Discarding Unfillable Attributes
Source: https://laravel.com/docs/12.x/eloquent
This snippet shows how to instruct Laravel Eloquent to throw an exception when attempting to fill an attribute that is not defined in the model’s fillable array. Using Model::preventSilentlyDiscardingAttributes() can help catch unexpected errors during development by making such actions explicit.
Model::preventSilentlyDiscardingAttributes(! $this->app->isProduction());
Define Broadcast Connection in Event Constructor (PHP)
Source: https://laravel.com/docs/12.x/broadcasting
Alternatively, you can specify the broadcast connection directly within the event’s constructor. Ensure the event class uses the ‘InteractsWithBroadcasting’ trait for the ‘broadcastVia’ method to be available.
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithBroadcasting;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class OrderShipmentStatusUpdated implements ShouldBroadcast
{
use InteractsWithBroadcasting;
/**
* Create a new event instance.
*/
public function __construct()
{
$this->broadcastVia('pusher');
}
}
Publish Laravel Scout configuration file
Source: https://laravel.com/docs/12.x/scout
After installing Scout, publish its configuration file to your application’s config directory. This allows you to customize various settings for Scout’s behavior.
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
Swap Subscription Price (PHP)
Source: https://laravel.com/docs/12.x/billing
Demonstrates how to change a customer’s subscription to a new price using the swap method. This method takes the Stripe price identifier and will reactivate canceled subscriptions while maintaining trial periods and quantities.
use App\Models\User;
$user = App\Models\User::find(1);
$user->subscription('default')->swap('price_yearly');
Execute Basic SELECT Query with Parameter Binding in Laravel
Source: https://laravel.com/docs/12.x/database
This snippet demonstrates how to run a basic SELECT SQL query using Laravel’s DB::select method. It shows how to pass parameter bindings to prevent SQL injection and how the method returns an array of stdClass objects, each representing a database record. The second example illustrates iterating over these results.
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
class UserController extends Controller
{
/**
* Show a list of all of the application's users.
*/
public function index(): View
{
$users = DB::select('select * from users where active = ?', [1]);
return view('user.index', ['users' => $users]);
}
}
use Illuminate\Support\Facades\DB;
$users = DB::select('select * from users');
foreach ($users as $user) {
echo $user->name;
}
Mock Laravel Cache Facade’s Get Method for Testing
Source: https://laravel.com/docs/12.x/mocking
This code demonstrates how to mock the get method of the Cache facade during testing using Mockery. It sets up an expectation for the get method with specific arguments and defines a return value, allowing you to isolate the component being tested.
<?php
use IlluminateSupportFacadesCache;
test('get index', function () {
Cache::expects('get')
->with('key')
->andReturn('value');
$response = $this->get('/users');
// ...
});
<?php
namespace TestsFeature;
use IlluminateSupportFacadesCache;
use TestsTestCase;
class UserControllerTest extends TestCase
{
public function test_get_index(): void
{
Cache::expects('get')
->with('key')
->andReturn('value');
$response = $this->get('/users');
// ...
}
}
Customize Laravel Prompts multisearch with Placeholder and Hint
Source: https://laravel.com/docs/12.x/prompts
Explains how to enhance user experience in multisearch by adding a placeholder text and an informational hint. This provides guidance to the user on expected input and the immediate consequence of their selection.
$ids = multisearch(
label: 'Search for the users that should receive the mail',
placeholder: 'E.g. Taylor Otwell',
options: fn (string $value) => strlen($value) > 0
? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
: [],
hint: 'The user will receive an email immediately.'
);
Provide Payment Confirmation Options for Laravel Cashier Swaps
Source: https://laravel.com/docs/12.x/billing
This PHP code demonstrates how to use the withPaymentConfirmationOptions method when swapping a subscription to include additional data required for payment confirmation, such as mandate_data for SEPA payments. This is crucial for complying with specific payment method requirements and ensuring successful payment processing. The options are passed as an associative array to the method before performing the swap operation.
$subscription->withPaymentConfirmationOptions([
'mandate_data' => '...',
])->swap('price_xxx');
Create Laravel Cashier Paddle Subscription Checkout Session (PHP)
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP code snippet demonstrates how to initiate a Paddle checkout session for a user. It uses the subscribe method on the billable model, specifying the Paddle price ID and an internal subscription type, and includes a returnTo URL for post-checkout redirection.
use Illuminate\Http\Request;
Route::get('/user/subscribe', function (Request $request) {
$checkout = $request->user()->subscribe($premium = 'pri_123', 'default')
->returnTo(route('home'));
return view('billing', ['checkout' => $checkout]);
});
Delete Specific Payment Method by ID from Billable Model in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP example shows how to delete a payment method from a billable model (e.g., User) using its Stripe payment method ID. The deletePaymentMethod method removes the specified payment method associated with the user.
$user->deletePaymentMethod('pm_visa');
Start Verbose Laravel Queue Worker (Shell)
Source: https://laravel.com/docs/12.x/queues
This command starts a Laravel queue worker with verbose output enabled using the -v flag. When active, it displays processed job IDs, connection names, and queue names in the console, which is useful for debugging and monitoring.
php artisan queue:work -v
Change Default CLI PHP Version in Homestead
Source: https://laravel.com/docs/12.x/homestead
These shell commands are used inside the Homestead virtual machine to switch the default PHP version used by the command-line interface. Executing one of these commands will symlink the global php binary to the specified version, affecting subsequent CLI commands.
php56
php70
php71
php72
php73
php74
php80
php81
php82
php83
Laravel Cashier Paddle: Initiate Product Checkout Route
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP snippet defines a Laravel route that initiates a Paddle Checkout Overlay for a specific product. It uses Cashier’s checkout method to create a checkout object, allowing the user to provide payment details. Upon successful payment, the customer is redirected to the specified return URL.
use Illuminate\Http\Request;
Route::get('/buy', function (Request $request) {
$checkout = $request->user()->checkout('pri_deluxe_album')
->returnTo(route('dashboard'));
return view('buy', ['checkout' => $checkout]);
})->name('checkout');
Start a Laravel Queue Worker (Shell)
Source: https://laravel.com/docs/12.x/queues
This shell command starts a Laravel queue worker that continuously processes jobs from the queue. The worker runs until manually stopped or the terminal is closed, and it’s recommended to use a process monitor like Supervisor for production environments.
php artisan queue:work
Invoice Item with Discounts and Default Tax Rates (PHP)
Source: https://laravel.com/docs/12.x/billing
Illustrates how to apply discounts and specify default tax rates when invoicing an item using the invoicePrice method. The method accepts additional arrays for billing options on the invoice item and the invoice itself, respectively.
$user->invoicePrice('price_tshirt', 5, [
'discounts' => [
['coupon' => 'SUMMER21SALE']
]
], [
'default_tax_rates' => ['txr_id']
]);
Start Laravel Pulse Daemon for Polling Recorders
Source: https://laravel.com/docs/12.x/pulse
This Artisan command starts the pulse:check daemon, which is necessary for Pulse recorders that poll for information, such as the servers recorder. It should be run on all application servers and managed with a process monitor like Supervisor for continuous operation.
php artisan pulse:check
Assert URL path is exact in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the current path matches the given path exactly. This ensures the URL’s path is precisely as expected.
$browser->assertPathIs('/home');
Install Laravel Envoy with Composer
Source: https://laravel.com/docs/12.x/envoy
Installs the Laravel Envoy package into your project as a development dependency using Composer. This makes the Envoy binary available for remote task execution.
composer require laravel/envoy --dev
Broadcast Simple Anonymous Event (PHP)
Source: https://laravel.com/docs/12.x/broadcasting
Laravel allows broadcasting ‘anonymous events’ without needing to create a dedicated event class. Use the ‘Broadcast::on()’ method to specify the channel and then call ‘send()’ to dispatch it.
Broadcast::on('orders.'.$order->id)->send();
Implement Deferred Service Provider in Laravel (PHP)
Source: https://laravel.com/docs/12.x/providers
This example shows how to create a deferred service provider in Laravel to improve application performance. By implementing DeferrableProvider and defining a provides method, the provider’s registration is deferred until one of its registered bindings is actually needed.
<?php
namespace AppProviders;
use AppServicesRiakConnection;
use IlluminateContractsFoundationApplication;
use IlluminateContractsSupportDeferrableProvider;
use IlluminateSupportServiceProvider;
class RiakServiceProvider extends ServiceProvider implements DeferrableProvider
{
/**
* Register any application services.
*/
public function register(): void
{
$this->app->singleton(Connection::class, function (Application $app) {
return new Connection($app['config']['riak']);
});
}
/**
* Get the services provided by the provider.
*
* @return array<int, string>
*/
public function provides(): array
{
return [Connection::class];
}
}
Displaying Informational Messages in Laravel Prompts (PHP)
Source: https://laravel.com/docs/12.x/prompts
This example shows how to use the info function from Laravel Prompts to display a standard informational message to the user in a command-line interface. Similar functions like note, warning, error, and alert are also available.
use function Laravel\Prompts\info;
info('Package installed successfully.');
List All Meters for a Customer in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP snippet retrieves a list of all meters associated with a customer’s subscriptions. It utilizes the meters method available on the Billable model to access meter information.
$user = User::find(1);
$user->meters();
Listen for Public Events with Laravel Echo (JavaScript)
Source: https://laravel.com/docs/12.x/broadcasting
After installing Laravel Echo, you can listen for events broadcast from your Laravel application. Use ‘Echo.channel()’ to specify the public channel and ‘.listen()’ to subscribe to a particular event name.
Echo.channel(`orders.${this.order.id}`).listen('OrderShipmentStatusUpdated', (e) => {
console.log(e.order.name);
});
Switch React Application Layout
Source: https://laravel.com/docs/12.x/starter-kits
This JavaScript snippet illustrates how to change the primary application layout in a React starter kit. By modifying the import statement in resources/js/layouts/app-layout.tsx, users can switch between a default sidebar layout and an alternative header layout.
import AppLayoutTemplate from '@/layouts/app/app-sidebar-layout'; // [tl! remove]
import AppLayoutTemplate from '@/layouts/app/app-header-layout'; // [tl! add]
Understand Laravel Container Class Dependency Resolution in 12.x
Source: https://laravel.com/docs/12.x/upgrade
This PHP example illustrates a change in Laravel 12 where the dependency injection container now respects default values of class properties. Previously, the container might have resolved an instance even if a default null was present, but now it will honor the default, potentially returning null.
class Example
{
public function __construct(public ?Carbon $date = null) {}
}
$example = resolve(Example::class);
// <= 11.x
$example->date instanceof Carbon;
// >= 12.x
$example->date === null;
Install MongoDB PHP Extension via PECL
Source: https://laravel.com/docs/12.x/mongodb
To enable PHP applications to connect to a MongoDB database, the mongodb PHP extension is required. This command uses PECL to manually install the extension if it’s not already bundled with your PHP environment.
pecl install mongodb
Register Application Services in Laravel Service Provider Boot Method (PHP)
Source: https://laravel.com/docs/12.x/providers
This code demonstrates how to register application services, such as view composers, within the boot method of a Laravel service provider. The boot method is executed after all other service providers have been registered, ensuring access to all framework services.
<?php
namespace AppProviders;
use IlluminateSupportFacadesView;
use IlluminateSupportServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
View::composer('view', function () {
// ...
});
}
}
Inspect Incomplete Payment Exception Status in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP snippet illustrates how to inspect the payment property of an IncompletePayment exception to get detailed status information about a failed payment intent. It demonstrates accessing the payment’s status and checking specific conditions like requiresPaymentMethod() or requiresConfirmation(). This allows for fine-grained error handling and user feedback based on the exact reason for the incomplete payment.
use Laravel\Cashier\Exceptions\IncompletePayment;
try {
$user->charge(1000, 'pm_card_threeDSecure2Required');
} catch (IncompletePayment $exception) {
// Get the payment intent status...
$exception->payment->status;
// Check specific conditions...
if ($exception->payment->requiresPaymentMethod()) {
// ...
} elseif ($exception->payment->requiresConfirmation()) {
// ...
}
}
Install Chokidar for Laravel Octane File Watching
Source: https://laravel.com/docs/12.x/octane
This command installs the Chokidar file-watching library as a development dependency. Chokidar is required for Laravel Octane’s --watch flag to detect and react to file changes efficiently.
npm install --save-dev chokidar
GET /oauth/authorize
Source: https://laravel.com/docs/12.x/passport
Redirects the user to the authorization server to initiate the PKCE authorization flow. The client sends authorization parameters, including the code challenge, to obtain an authorization code.
## GET /oauth/authorize
### Description
This endpoint is used to redirect a user to the authorization server to request an authorization code as part of the PKCE flow. The consuming application provides client details, redirect URI, scope, and the generated code challenge.
### Method
GET
### Endpoint
/oauth/authorize
### Parameters
#### Path Parameters
- No path parameters.
#### Query Parameters
- **client_id** (string) - Required - The client ID of the application.
- **redirect_uri** (string) - Required - The URI to redirect the user back to after authorization.
- **response_type** (string) - Required - Must be set to 'code'.
- **scope** (string) - Optional - A space-separated list of scopes the client is requesting.
- **state** (string) - Required - A random string generated by the client to maintain state between the request and callback, mitigating CSRF attacks.
- **code_challenge** (string) - Required - A Base64 URL-encoded SHA256 hash of the `code_verifier`.
- **code_challenge_method** (string) - Required - Must be 'S256' for SHA256.
- **prompt** (string) - Optional - Controls the user experience, e.g., "none", "consent", or "login".
### Request Example
GET /oauth/authorize?client_id=your-client-id&redirect_uri=https://third-party-app.com/callback&response_type=code&scope=user:read%20orders:create&state=random_state_string&code_challenge=code_challenge_string&code_challenge_method=S256
### Response
#### Success Response (302 Redirect)
Upon successful authorization, the user is redirected to the `redirect_uri` with an authorization code and the state parameter.
- **code** (string) - The authorization code.
- **state** (string) - The original state parameter.
#### Response Example
(Redirect to)
https://third-party-app.com/callback?code=authorization_code_string&state=random_state_string
Create Laravel Uri Instances
Source: https://laravel.com/docs/12.x/helpers
This snippet shows various methods to instantiate Laravel’s Uri class, which provides a fluent interface for URI handling based on League URI. You can create URIs from strings, paths, named routes (including signed and temporary signed routes), or controller actions. It also covers how to get a Uri instance from the current request.
use App\Http\Controllers\UserController;
use App\Http\Controllers\InvokableController;
use Illuminate\Support\Uri;
// Generate a URI instance from the given string...
$uri = Uri::of('https://example.com/path');
// Generate URI instances to paths, named routes, or controller actions...
$uri = Uri::to('/dashboard');
$uri = Uri::route('users.show', ['user' => 1]);
$uri = Uri::signedRoute('users.show', ['user' => 1]);
$uri = Uri::temporarySignedRoute('user.index', now()->addMinutes(5));
$uri = Uri::action([UserController::class, 'index']);
$uri = Uri::action(InvokableController::class);
// Generate a URI instance from the current request URL...
$uri = $request->uri();
Store a file using Laravel’s local disk
Source: https://laravel.com/docs/12.x/filesystem
This PHP snippet demonstrates how to store content to a file named ‘example.txt’ using Laravel’s default ‘local’ storage disk. By default, the file will be saved in the storage/app/private directory relative to the application’s root.
use Illuminate\Support\Facades\Storage;
Storage::disk('local')->put('example.txt', 'Contents');
Initiate a basic guest checkout session in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP snippet demonstrates how to initiate a basic guest checkout session for a product using Laravel Cashier’s Checkout::guest() method within a Laravel route. It creates a Stripe checkout session for a specified price ID (‘price_tshirt’) and provides success and cancel URLs for redirection after the checkout process.
use Illuminate\Http\Request;
use Laravel\Cashier\Checkout;
Route::get('/product-checkout', function (Request $request) {
return Checkout::guest()->create('price_tshirt', [
'success_url' => route('your-success-route'),
'cancel_url' => route('your-cancel-route'),
]);
});
Schedule a Shell Command in Laravel PHP
Source: https://laravel.com/docs/12.x/scheduling
Illustrates how to schedule a shell command to be executed by the operating system using Laravel’s Schedule::exec method. This example runs a Node.js script daily.
use Illuminate\Support\Facades\Schedule;
Schedule::exec('node /home/forge/script.js')->daily();
Configure Cron Scheduling for a Homestead Site
Source: https://laravel.com/docs/12.x/homestead
This YAML configuration enables cron job scheduling for a specific Homestead site. By setting the schedule option to true within a site’s definition in Homestead.yaml, the schedule:run Artisan command is automatically configured to run every minute for that site, processing scheduled tasks defined in your Laravel application.
sites:
- map: homestead.test
to: /home/vagrant/project1/public
schedule: true
Start Laravel Octane Server via Artisan Command
Source: https://laravel.com/docs/12.x/octane
This shell command initiates the Laravel Octane server using the Artisan command-line tool. By default, it utilizes the server specified in the Octane configuration file and typically starts on port 8000.
php artisan octane:start
Handle Multiple OS Signals in Laravel Artisan Command
Source: https://laravel.com/docs/12.x/artisan
Demonstrates how to register a single callback to respond to multiple operating system signals, such as SIGTERM and SIGQUIT. The trap method accepts an array of signals and a callback function which receives the triggered signal as an argument.
$this->trap([SIGTERM, SIGQUIT], function (int $signal) {
$this->shouldKeepRunning = false;
dump($signal); // SIGTERM / SIGQUIT
});
Register Custom Cashier Models in Laravel
Source: https://laravel.com/docs/12.x/billing
After defining custom models for Cashier, this PHP snippet illustrates how to inform Cashier to use these models instead of its defaults. This registration process is typically performed in the boot method of your AppServiceProvider, ensuring that Cashier utilizes your custom Subscription and SubscriptionItem models throughout the application.
use App\Models\Cashier\Subscription;
use App\Models\Cashier\SubscriptionItem;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Cashier::useSubscriptionModel(Subscription::class);
Cashier::useSubscriptionItemModel(SubscriptionItem::class);
}
Credit Customer’s Balance
Source: https://laravel.com/docs/12.x/billing
Adds a specified amount to a customer’s balance, effectively crediting their account. An optional description can be provided to explain the reason for the credit, which will appear on future invoices.
$user->creditBalance(500, 'Premium customer top-up.');
Start Asynchronous Process and Wait in Laravel
Source: https://laravel.com/docs/12.x/processes
The start method allows invoking a process asynchronously, letting the application continue execution. The running() method can check if the process is still active, and wait() will block until the process completes, returning the ProcessResult.
$process = Process::timeout(120)->start('bash import.sh');
while ($process->running()) {
// ...
}
$result = $process->wait();
Set Stripe API Keys in Laravel .env File
Source: https://laravel.com/docs/12.x/billing
This .env configuration defines the necessary Stripe API keys for your Laravel application. STRIPE_KEY and STRIPE_SECRET are used for API interactions, while STRIPE_WEBHOOK_SECRET secures incoming Stripe webhooks.
STRIPE_KEY=your-stripe-key
STRIPE_SECRET=your-stripe-secret
STRIPE_WEBHOOK_SECRET=your-stripe-webhook-secret
Install Mailgun Driver for Symfony Mailer
Source: https://laravel.com/docs/12.x/mail
This Composer command installs the necessary packages for integrating the Symfony Mailgun Mailer transport and HTTP client into your Laravel application, enabling email sending via Mailgun.
composer require symfony/mailgun-mailer symfony/http-client
Customize Paddle Checkout Button Theme in Blade (HTML)
Source: https://laravel.com/docs/12.x/cashier-paddle
This Blade component example demonstrates how to customize the Paddle Checkout Overlay widget’s appearance directly from the HTML. By adding data-theme='light' as a prop, developers can modify the widget’s styling. It still relies on a checkout session prop to define the billing operation.
<x-paddle-button :checkout="$checkout" class="px-8 py-4" data-theme="light"> Subscribe </x-paddle-button>
Install Swoole PHP Extension via PECL
Source: https://laravel.com/docs/12.x/octane
This command installs the Swoole PHP extension using PECL (PHP Extension Community Library). The Swoole extension is a prerequisite for using the Swoole application server with Laravel Octane, enabling high-performance features.
pecl install swoole
Define Laravel Artisan Command Class Structure
Source: https://laravel.com/docs/12.x/artisan
This PHP example demonstrates the structure of a Laravel Artisan command class. It defines the command signature, description, and implements the handle method for command logic, leveraging Laravel’s service container for dependency injection.
<?php
namespace App\Console\Commands;
use App\Models\User;
use App\Support\DripEmailer;
use Illuminate\Console\Command;
class SendEmails extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mail:send {user}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send a marketing email to a user';
/**
* Execute the console command.
*/
public function handle(DripEmailer $drip): void
{
$drip->send(User::find($this->argument('user')));
}
}
Replace String at Start in PHP (Str::replaceStart)
Source: https://laravel.com/docs/12.x/strings
The Str::replaceStart method replaces the first occurrence of a specified value, but only if that value appears at the very beginning of the string. If the string does not start with the value, no replacement occurs.
use Illuminate\Support\Str;
$replaced = Str::replaceStart('Hello', 'Laravel', 'Hello World');
// Laravel World
$replaced = Str::replaceStart('World', 'Laravel', 'Hello World');
// Hello World
Configure Laravel Application to Use Mailpit
Source: https://laravel.com/docs/12.x/homestead
This snippet provides the necessary .env file settings to configure a Laravel application to use Mailpit for email interception. It directs outgoing email via SMTP to localhost on port 1025, allowing you to examine emails without actually sending them to recipients.
MAIL_MAILER=smtp
MAIL_HOST=localhost
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
Move Browser Window to Specific Coordinates with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This snippet illustrates how to use the move method to reposition the browser window on the screen using X and Y coordinates. This can be useful for arranging multiple browser windows during tests or placing them at a specific location for visibility.
$browser->move($x = 100, $y = 100);
Install Laravel Precognition Vue Inertia package via NPM
Source: https://laravel.com/docs/12.x/precognition
This shell command installs the laravel-precognition-vue-inertia package, which is essential for integrating Laravel Precognition’s validation features with Vue.js and Inertia.js applications. This package augments Inertia’s useForm helper with Precognition capabilities.
npm install laravel-precognition-vue-inertia
Make Basic GET Request in Laravel HTTP Client
Source: https://laravel.com/docs/12.x/http-client
This snippet demonstrates how to send a basic GET request to a URL using Laravel’s Http facade. It returns an instance of Illuminate\Http\Client\Response for further inspection.
use Illuminate\Support\Facades\Http;
$response = Http::get('http://example.com');
Link to Cashier Payment Confirmation Page (HTML)
Source: https://laravel.com/docs/12.x/billing
Provides an HTML anchor tag to direct users to Cashier’s payment confirmation page. It uses the latestPayment()->id from the subscription instance to construct the URL for payment completion.
<a href="{{ route('cashier.payment', $subscription->latestPayment()->id) }}"> Please confirm your payment. </a>
Test Laravel Facade Interaction with Pest and PHPUnit
Source: https://laravel.com/docs/12.x/facades
This snippet illustrates how to test interactions with Laravel facades by mocking the Cache facade using shouldReceive. It includes examples for both Pest and PHPUnit testing frameworks, verifying that Cache::get was called with expected arguments and asserting the response content.
use Illuminate\Support\Facades\Cache;
test('basic example', function () {
Cache::shouldReceive('get')
->with('key')
->andReturn('value');
$response = $this->get('/cache');
$response->assertSee('value');
});
use Illuminate\Support\Facades\Cache;
/**
* A basic functional test example.
*/
public function test_basic_example(): void
{
Cache::shouldReceive('get')
->with('key')
->andReturn('value');
$response = $this->get('/cache');
$response->assertSee('value');
}
Check if String Does Not Start With Value with Laravel Str::doesntStartWith()
Source: https://laravel.com/docs/12.x/strings
The Str::doesntStartWith method determines if a string does not begin with a specified value. It can also evaluate against an array of potential starting values, returning true if none of them match.
use Illuminate\Support\Str;
$result = Str::doesntStartWith('This is my name', 'That');
// true
use Illuminate\Support\Str;
$result = Str::doesntStartWith('This is my name', ['What', 'That', 'There']);
// true
Define Custom Keyboard Macros in Laravel Dusk PHP
Source: https://laravel.com/docs/12.x/dusk
This PHP code defines ‘copy’ and ‘paste’ keyboard macros using Laravel Dusk’s Keyboard::macro method within a service provider’s boot method. These macros use WebDriverKeys::META or WebDriverKeys::CONTROL based on the operating system to simulate common keyboard shortcuts, making them reusable throughout your test suite.
<?php
namespace AppProviders;
use Facebook\WebDriver\WebDriverKeys;
use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\Keyboard;
use Laravel\Dusk\OperatingSystem;
class DuskServiceProvider extends ServiceProvider
{
/**
* Register Dusk's browser macros.
*/
public function boot(): void
{
Keyboard::macro('copy', function (string $element = null) {
$this->type([
OperatingSystem::onMac() ? WebDriverKeys::META : WebDriverKeys::CONTROL, 'c',
]);
return $this;
});
Keyboard::macro('paste', function (string $element = null) {
$this->type([
OperatingSystem::onMac() ? WebDriverKeys::META : WebDriverKeys::CONTROL, 'v',
]);
return $this;
});
}
}
Start and Stop Laravel Sail Docker Containers
Source: https://laravel.com/docs/12.x/sail
These commands control the lifecycle of Laravel Sail’s Docker containers. Use up to start them, up -d for detached background execution, and stop to gracefully shut them down.
sail up
sail up -d
sail stop
Preview subscription invoice with a single new price in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
Allows previewing how an invoice will look after a price change for a subscription without actually making the change. Use the previewInvoice method with a single new price ID.
$invoice = $user->subscription('default')->previewInvoice('price_yearly');
Check Eloquent Model Attributes Changed on Last Save with wasChanged (PHP)
Source: https://laravel.com/docs/12.x/eloquent
This snippet illustrates the wasChanged method, which determines if attributes were modified during the model’s last save operation within the current request cycle. It can be used to check all attributes or specific ones by passing an attribute name or an array of names.
$user = User::create([
'first_name' => 'Taylor',
'last_name' => 'Otwell',
'title' => 'Developer',
]);
$user->title = 'Painter';
$user->save();
$user->wasChanged(); // true
$user->wasChanged('title'); // true
$user->wasChanged(['title', 'slug']); // true
$user->wasChanged('first_name'); // false
$user->wasChanged(['first_name', 'title']); // true
Change React Authentication Page Layout
Source: https://laravel.com/docs/12.x/starter-kits
This JavaScript snippet shows how to switch the layout for authentication pages in a React starter kit. By modifying the import statement in resources/js/layouts/auth-layout.tsx, users can choose between ‘simple’, ‘card’, or ‘split’ authentication layouts.
import AuthLayoutTemplate from '@/layouts/auth/auth-simple-layout'; // [tl! remove]
import AuthLayoutTemplate from '@/layouts/auth/auth-split-layout'; // [tl! add]
Check if String Starts With Value(s) in PHP (Str::startsWith)
Source: https://laravel.com/docs/12.x/strings
The Str::startsWith method determines if a string begins with a specified value. It can also accept an array of values, returning true if the string starts with any one of them.
use Illuminate\Support\Str;
$result = Str::startsWith('This is my name', 'This');
// true
use Illuminate\Support\Str;
$result = Str::startsWith('This is my name', ['This', 'That', 'There']);
// true
Execute Code Before/After Database Truncation (PHP)
Source: https://laravel.com/docs/12.x/dusk
Implement beforeTruncatingDatabase and afterTruncatingDatabase methods in your test class to execute custom logic immediately before or after the database truncation process. This provides hooks for setting up or tearing down specific test conditions related to database state.
/**
* Perform any work that should take place before the database has started truncating.
*/
protected function beforeTruncatingDatabase(): void
{
//
}
/**
* Perform any work that should take place after the database has finished truncating.
*/
protected function afterTruncatingDatabase(): void
{
//
}
Retrieve all invoices for a billable model in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
Fetches a collection of all Laravel\Cashier\Invoice instances associated with a billable model using the invoices method. This provides a list of past and current invoices.
$invoices = $user->invoices();
Generate Passport Encryption Keys for Deployment
Source: https://laravel.com/docs/12.x/passport
Run this Artisan command when deploying Passport to your application’s servers for the first time. It generates the encryption keys that Passport requires to securely generate access tokens; these keys are typically excluded from source control.
php artisan passport:keys
Override Default UUID Generation and Specify Columns in Laravel Eloquent
Source: https://laravel.com/docs/12.x/eloquent
This PHP snippet illustrates how to customize the UUID generation logic for an Eloquent model by defining a newUniqueId method. It also shows how to specify multiple columns that should receive unique identifiers using the uniqueIds method, useful for fields beyond the primary key.
use Ramsey\Uuid\Uuid;
/**
* Generate a new UUID for the model.
*/
public function newUniqueId(): string
{
return (string) Uuid::uuid4();
}
/**
* Get the columns that should receive a unique identifier.
*
* @return array<int, string>
*/
public function uniqueIds(): array
{
return ['id', 'discount_code'];
}
Register Closure-based Event Listener in Laravel
Source: https://laravel.com/docs/12.x/events
This example shows how to manually register a closure-based event listener in the boot method of AppServiceProvider. This provides a flexible alternative to class-based listeners when the listener logic is simple and self-contained.
use App\Events\PodcastProcessed;
use Illuminate\Support\Facades\Event;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Event::listen(function (PodcastProcessed $event) {
// ...
});
}
Execute closure if Laravel Fluent String doesn’t start with substring with whenDoesntStartWith (PHP)
Source: https://laravel.com/docs/12.x/strings
The whenDoesntStartWith method invokes a closure if the string does not start with the given sub-string. The closure receives the fluent string instance.
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('disney world')->whenDoesntStartWith('sea', function (Stringable $string) {
return $string->title();
});
// 'Disney World'
Reference a nested Blade view using dot notation
Source: https://laravel.com/docs/12.x/views
This PHP example shows how to render a view located within a subdirectory (e.g., resources/views/admin/profile.blade.php) by using dot notation (e.g., 'admin.profile') with the view helper.
return view('admin.profile', $data);
Define Laravel HTTP Client Macro in AppServiceProvider
Source: https://laravel.com/docs/12.x/http-client
This example illustrates how to define a reusable macro for the Laravel HTTP client within the boot method of your App\Providers\AppServiceProvider. Macros provide a fluent and expressive way to configure common request paths and headers, such as setting a base URL and custom headers for GitHub API interactions.
use Illuminate\Support\Facades\Http;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Http::macro('github', function () {
return Http::withHeaders([
'X-Example' => 'example',
])->baseUrl('https://github.com');
});
}
Localize Resource Route Verbs in Laravel
Source: https://laravel.com/docs/12.x/controllers
This example shows how to localize the ‘create’ and ‘edit’ action verbs for resource URIs in Laravel. By calling Route::resourceVerbs() in your AppServiceProvider’s boot method, you can translate these verbs into different languages, supporting internationalization of your application’s routes. The publicacion example demonstrates the resulting localized URIs.
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Route::resourceVerbs([
'create' => 'crear',
'edit' => 'editar',
]);
}
/publicacion/crear
/publicacion/{publicaciones}/editar
Create Metered Subscription with Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP snippet demonstrates how to create a new subscription with a metered price using Laravel Cashier. It assumes a product with a usage-based billing model and an associated meter have been configured in your Stripe dashboard.
use Illuminate\Http\Request;
Route::post('/user/subscribe', function (Request $request) {
$request->user()->newSubscription('default')
->meteredPrice('price_metered')
->create($request->paymentMethodId);
// ...
});
Augment package.json Build Script for SSR
Source: https://laravel.com/docs/12.x/vite
To ensure the SSR entry point is rebuilt, modify the build script in your package.json file. Append an additional vite build --ssr command to the existing build script to create the SSR build alongside the regular client-side build, ensuring both are up-to-date.
"scripts": {
"dev": "vite",
"build": "vite build && vite build --ssr"
}
Add S3 Request Parameters to Laravel Temporary URLs
Source: https://laravel.com/docs/12.x/filesystem
When generating temporary URLs for S3, you might need to specify additional S3 request parameters for fine-grained control over the response (e.g., content disposition). This example illustrates passing an array of parameters as the third argument to the ‘temporaryUrl’ method to customize the S3 GET request.
$url = Storage::temporaryUrl(
'file.jpg',
now()->addMinutes(5),
[
'ResponseContentType' => 'application/octet-stream',
'ResponseContentDisposition' => 'attachment; filename=file2.jpg',
]
);
Defining a Laravel MCP Tool Class
Source: https://laravel.com/docs/12.x/mcp
Provides a comprehensive example of an Mcp\Server\Tool class. It includes the tool’s description, a handle method to process requests, and a schema method to define its input requirements using JsonSchema.
<?php
namespace App\Mcp\Tools;
use Illuminate\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
class CurrentWeatherTool extends Tool
{
/**
* The tool's description.
*/
protected string $description = 'Fetches the current weather forecast for a specified location.';
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$location = $request->get('location');
// Get weather...
return Response::text('The weather is...');
}
/**
* Get the tool's input schema.
*
* @return array<string, \Illuminate\JsonSchema\JsonSchema>
*/
public function schema(JsonSchema $schema): array
{
return [
'location' => $schema->string()
->description('The location to get the weather for.')
->required(),
];
}
}
Specify Broadcast Connection via ‘via’ Method (PHP)
Source: https://laravel.com/docs/12.x/broadcasting
To broadcast an event using a connection other than the default, you can chain the ‘via’ method to your broadcast call. This allows dynamic selection of the broadcaster for a specific event instance.
use App\Events\OrderShipmentStatusUpdated;
broadcast(new OrderShipmentStatusUpdated($update))->via('pusher');
Generate a new Laravel MCP prompt using Artisan
Source: https://laravel.com/docs/12.x/mcp
This shell command demonstrates how to use Laravel’s Artisan command-line interface to create a new Model Context Protocol (MCP) prompt class. Running this command generates a boilerplate PHP file, named DescribeWeatherPrompt in this example, which can then be customized with specific prompt logic and metadata.
php artisan make:mcp-prompt DescribeWeatherPrompt
Handle Failed Charges with Try-Catch Block (PHP)
Source: https://laravel.com/docs/12.x/billing
Shows how to gracefully handle potential exceptions that may occur if a charge fails. The charge method will throw an exception upon failure, which can be caught to implement custom error handling logic.
try {
$payment = $user->charge(100, $paymentMethod);
} catch (Exception $e) {
// ...
}
Implement a Custom Invoice Renderer in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
Create a custom invoice renderer by implementing the ‘Laravel\Cashier\Contracts\InvoiceRenderer’ interface. This allows for flexible PDF generation using external services or custom logic, such as an API call to a third-party HTML-to-PDF service.
use Illuminate\Support\Facades\Http;
use Laravel\Cashier\Contracts\InvoiceRenderer;
use Laravel\Cashier\Invoice;
class ApiInvoiceRenderer implements InvoiceRenderer
{
/**
* Render the given invoice and return the raw PDF bytes.
*/
public function render(Invoice $invoice, array $data = [], array $options = []): string
{
$html = $invoice->view($data)->render();
return Http::get('https://example.com/html-to-pdf', ['html' => $html])->get()->body();
}
}
Attach File to Input with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
The attach method uploads a file to a file input element. It identifies the element by a CSS selector or its name attribute. This function requires the Zip PHP extension to be enabled.
$browser->attach('photo', __DIR__.'/photos/mountains.png');
Laravel Dusk: Customizing the selector HTML attribute
Source: https://laravel.com/docs/12.x/dusk
This code shows how to customize the HTML attribute used for Dusk selectors from the default dusk to a different attribute, such as data-dusk. This customization is typically done in the boot method of your AppServiceProvider.
use Laravel\Dusk\Dusk;
Dusk::selectorHtmlAttribute('data-dusk');
Retrieve Customer Meter Event Summaries with Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP code fetches aggregated usage data for a specific meter for a customer. It uses the meterEventSummaries method on the Billable instance to retrieve billing period summaries.
$user = User::find(1);
$meterUsage = $user->meterEventSummaries($meterId);
$meterUsage->first()->aggregated_value // 10
Query Subscriptions by State Using Scopes (PHP)
Source: https://laravel.com/docs/12.x/cashier-paddle
Demonstrates how to use various query scopes provided by Laravel Cashier to filter subscriptions based on their specific status (e.g., valid, on trial, past due, canceled). These scopes simplify querying your database for subscriptions in different states.
// Get all valid subscriptions...
$subscriptions = Subscription::query()->valid()->get();
// Get all of the canceled subscriptions for a user...
$subscriptions = $user->subscriptions()->canceled()->get();
Subscription::query()->valid();
Subscription::query()->onTrial();
Subscription::query()->expiredTrial();
Subscription::query()->notOnTrial();
Subscription::query()->active();
Subscription::query()->recurring();
Subscription::query()->pastDue();
Subscription::query()->paused();
Subscription::query()->notPaused();
Subscription::query()->onPausedGracePeriod();
Subscription::query()->notOnPausedGracePeriod();
Subscription::query()->canceled();
Subscription::query()->notCanceled();
Subscription::query()->onGracePeriod();
Subscription::query()->notOnGracePeriod();
Run Concurrent Tasks with Laravel Concurrency Facade
Source: https://laravel.com/docs/12.x/concurrency
This example demonstrates how to use Laravel’s Concurrency::run method to execute multiple closures simultaneously. It fetches the count of users and orders from the database concurrently, returning an array of results.
use Illuminate\Support\Facades\Concurrency;
use Illuminate\Support\Facades\DB;
[$userCount, $orderCount] = Concurrency::run([
fn () => DB::table('users')->count(),
fn () => DB::table('orders')->count(),
]);
Apply Coupon to New Laravel Cashier Subscription
Source: https://laravel.com/docs/12.x/billing
This PHP snippet demonstrates how to apply a coupon code when creating a new subscription using Laravel Cashier. It utilizes the withCoupon method on the subscription builder before calling create to finalize the subscription with the specified coupon.
$user->newSubscription('default', 'price_monthly')
->withCoupon('code')
->create($paymentMethod);
Download an Invoice PDF in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
Utilize the ‘downloadInvoice’ method within a route or controller to generate and download a PDF for a specified invoice. This method automatically constructs the appropriate HTTP response required for the download operation.
use Illuminate\Http\Request;
Route::get('/user/invoice/{invoice}', function (Request $request, string $invoiceId) {
return $request->user()->downloadInvoice($invoiceId);
});
Listen to typed events with useEcho hook (TypeScript)
Source: https://laravel.com/docs/12.x/broadcasting
This TypeScript snippet illustrates how to provide type safety for the event payload when using the useEcho hook. By defining an interface or type for the expected event data, you gain better autocompletion, compile-time error checking, and improved code readability.
type OrderData = {
order: {
id: number;
user: {
id: number;
name: string;
};
created_at: string;
};
};
useEcho<OrderData>(`orders.${orderId}`, 'OrderShipmentStatusUpdated', (e) => {
console.log(e.order.id);
console.log(e.order.user.id);
});
Configure MySQL Database in Laravel .env File
Source: https://laravel.com/docs/12.x/installation
This .env file snippet shows how to configure your Laravel application to connect to a MySQL database. Update these variables (DB_CONNECTION, DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, DB_PASSWORD) with your specific MySQL server credentials.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Test Laravel Console Command with Mocked Questions and Output Assertions
Source: https://laravel.com/docs/12.x/console-tests
This snippet illustrates how to test a Laravel console command by mocking user answers to questions using expectsQuestion, asserting specific full output with expectsOutput, checking for the absence of specific output with doesntExpectOutput, and verifying the command’s exit code with assertExitCode. This example shows both Pest and PHPUnit syntax.
test('console command', function () {
$this->artisan('question')
->expectsQuestion('What is your name?', 'Taylor Otwell')
->expectsQuestion('Which language do you prefer?', 'PHP')
->expectsOutput('Your name is Taylor Otwell and you prefer PHP.')
->doesntExpectOutput('Your name is Taylor Otwell and you prefer Ruby.')
->assertExitCode(0);
});
/**
* Test a console command.
*/
public function test_console_command(): void
{
$this->artisan('question')
->expectsQuestion('What is your name?', 'Taylor Otwell')
->expectsQuestion('Which language do you prefer?', 'PHP')
->expectsOutput('Your name is Taylor Otwell and you prefer PHP.')
->doesntExpectOutput('Your name is Taylor Otwell and you prefer Ruby.')
->assertExitCode(0);
}
Install Laravel Slack Notification Channel
Source: https://laravel.com/docs/12.x/notifications
This command installs the necessary Composer package for sending Slack notifications within a Laravel application. It adds the laravel/slack-notification-channel dependency to your project, enabling the functionality to send messages to Slack.
composer require laravel/slack-notification-channel
Retrieve Cache Items with Default Values in Laravel (PHP)
Source: https://laravel.com/docs/12.x/cache
These PHP examples demonstrate retrieving items from the cache using Cache::get(). The first example returns null if the key doesn’t exist, while the second provides a static default value to be returned instead.
$value = Cache::get('key');
$value = Cache::get('key', 'default');
Replace string at start in Laravel Str::of() fluent API
Source: https://laravel.com/docs/12.x/strings
The replaceStart method replaces the first occurrence of a given value only if that value appears at the very beginning of the string. If the value is not at the start, no replacement occurs.
use Illuminate\Support\Str;
$replaced = Str::of('Hello World')->replaceStart('Hello', 'Laravel');
// Laravel World
$replaced = Str::of('Hello World')->replaceStart('World', 'Laravel');
// Hello World
Rescue Broadcast Exceptions with ‘ShouldRescue’ Interface (PHP)
Source: https://laravel.com/docs/12.x/broadcasting
Implement the ‘ShouldRescue’ interface on an event to gracefully handle broadcast failures. This ensures that exceptions during broadcasting are caught, logged, and do not interrupt the user’s application experience.
<?php
namespace App\Events;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Broadcasting\ShouldRescue;
class ServerCreated implements ShouldBroadcast, ShouldRescue
{
// ...
}
Broadcast Event to Presence Channel with Laravel PHP
Source: https://laravel.com/docs/12.x/broadcasting
This PHP snippet demonstrates how to use the broadcast helper function to dispatch an event to a presence channel. It also shows how to use the toOthers() method to prevent the event from being broadcast back to the user who triggered it, useful for preventing self-reception of messages.
broadcast(new NewMessage($message));
broadcast(new NewMessage($message))->toOthers();
Send Keyboard Shortcut to Element with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
The keys method can also send keyboard shortcut combinations to a specified element. This is useful for application-wide shortcuts, using {command} or similar modifiers.
$browser->keys('.app', ['{command}', 'j']);
Customize Search Prompt with Placeholder and Hint (Laravel PHP)
Source: https://laravel.com/docs/12.x/prompts
Demonstrates how to add placeholder text and an informational hint to the search function. These options provide guidance to the user, making the search prompt more intuitive and user-friendly.
$id = search(
label: 'Search for the user that should receive the mail',
placeholder: 'E.g. Taylor Otwell',
options: fn (string $value) => strlen($value) > 0
? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
: [],
hint: 'The user will receive an email immediately.'
);
Install Laravel Folio package via Composer
Source: https://laravel.com/docs/12.x/folio
This command installs the Laravel Folio package into your project using the Composer package manager. It adds the necessary dependencies for Folio to function correctly within your Laravel application.
composer require laravel/folio
Create Blade Link for Stripe Billing Portal
Source: https://laravel.com/docs/12.x/billing
Defines an HTML anchor tag in Blade to direct users to a Laravel route that initiates a Stripe Billing Portal session. This link typically appears in the user interface to allow customers to manage their subscriptions and billing information.
<a href="{{ route('billing') }}">
Billing
</a>
End Subscription Trial Immediately (PHP)
Source: https://laravel.com/docs/12.x/billing
This code demonstrates how to immediately terminate an ongoing trial for a specific subscription using the endTrial method. This action will typically transition the subscription to a paid status if a payment method is attached.
$user->subscription('default')->endTrial();
Check if string does not start with value(s) using Laravel Str::of
Source: https://laravel.com/docs/12.x/strings
The doesntStartWith method determines if a string does not begin with a specified prefix or any of a list of prefixes. It returns true if none of the provided prefixes are found at the beginning of the string.
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntStartWith('That');
// true
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntStartWith(['What', 'That', 'There']);
// true
Use Eloquent Model in Channel Constructor for Broadcasting (PHP)
Source: https://laravel.com/docs/12.x/broadcasting
This PHP snippet demonstrates returning a Channel instance from the broadcastOn method, passing an Eloquent model directly to its constructor. Laravel then automatically converts the model into a channel name string based on its conventions.
return [new Channel($this->user)];
List Laravel Broadcast Channel Authorization Callbacks
Source: https://laravel.com/docs/12.x/broadcasting
This shell command allows developers to view a list of all registered broadcast authorization callbacks within their Laravel application. Running php artisan channel:list provides an overview of defined channel authorization logic, which is useful for debugging and understanding access control for broadcast channels.
php artisan channel:list
Spoof HTML Form Methods using Hidden Input in Laravel Blade
Source: https://laravel.com/docs/12.x/routing
This Blade template example illustrates how to spoof HTTP methods like PUT in HTML forms, which natively only support GET and POST. It achieves this by including a hidden input field named _method with the desired HTTP verb, along with a CSRF token for security.
<form action="/example" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
Create value object from multiple attributes using Eloquent accessor in PHP
Source: https://laravel.com/docs/12.x/eloquent-mutators
This PHP example demonstrates how to define an Eloquent accessor (address) that combines multiple model attributes (address_line_one, address_line_two) into a single value object (Address). The get closure accepts a second $attributes argument, which provides an array of all the model’s current attributes, enabling complex value object construction.
use App\Support\Address;
use Illuminate\Database\Eloquent\Casts\Attribute;
/**
* Interact with the user's address.
*/
protected function address(): Attribute
{
return Attribute::make(
get: fn (mixed $value, array $attributes) => new Address(
$attributes['address_line_one'],
$attributes['address_line_two'],
),
);
}
Customize Anonymous Event Name and Data (PHP)
Source: https://laravel.com/docs/12.x/broadcasting
You can customize the name of an anonymous event using the ‘as’ method and provide custom data with the ‘with’ method. This allows more meaningful events without class creation.
Broadcast::on('orders.'.$order->id)
->as('OrderPlaced')
->with($order)
->send();
Retrieve Active Discounts for Laravel Cashier Billable or Subscription
Source: https://laravel.com/docs/12.x/billing
This PHP code illustrates how to retrieve the currently applied Laravel\Cashier\Discount instance from either a billable model (e.g., User) or a specific subscription. This allows inspection of any active discounts.
$discount = $billable->discount();
$discount = $subscription->discount();
Programmatically Create a Device Authorization Grant Client
Source: https://laravel.com/docs/12.x/passport
This PHP example demonstrates how to create a third-party device authorization grant client programmatically using the ClientRepository class. It allows assigning the client to a specific user and setting its name and confidentiality status.
use AppModelsUser;
use LaravelPassportClientRepository;
$user = User::find($userId);
$client = app(ClientRepository::class)->createDeviceAuthorizationGrantClient(
user: $user,
name: 'Example Device',
confidential: false,
);
Configure Laravel Vite Plugin for SSR
Source: https://laravel.com/docs/12.x/vite
To enable server-side rendering (SSR) with Vite in Laravel, create an SSR entry point (e.g., resources/js/ssr.js) and specify it in the laravel plugin configuration within your vite.config.js file using the ssr option. This setup is crucial for building SSR-enabled applications.
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
input: 'resources/js/app.js',
ssr: 'resources/js/ssr.js',
}),
],
});
Re-run Failing Laravel Dusk Tests (Shell)
Source: https://laravel.com/docs/12.x/dusk
Utilize php artisan dusk:fails to quickly re-run only the Laravel Dusk tests that failed during the last execution. This command streamlines the debugging process by focusing on problematic tests.
php artisan dusk:fails
Get all files within a directory using Laravel Storage
Source: https://laravel.com/docs/12.x/filesystem
This code demonstrates how to retrieve a list of all files within a specified directory using the Storage::files method. It also shows how to recursively get all files, including those in subdirectories, using Storage::allFiles.
use Illuminate\Support\Facades\Storage;
$files = Storage::files($directory);
$files = Storage::allFiles($directory);
CHANNEL_AUTH chat.{roomId}
Source: https://laravel.com/docs/12.x/broadcasting
This defines the server-side authorization logic for a Laravel Echo presence channel. It determines if an authenticated user is permitted to join a specific channel and, if so, returns an array of user-specific data to the client-side.
## CHANNEL_AUTH chat.{roomId}
### Description
Defines the server-side authorization logic for a presence channel. This callback determines if a user is permitted to join a specific channel and returns identifying user data upon successful authorization.
### Method
CHANNEL_AUTH
### Endpoint
chat.{roomId}
### Parameters
#### Path Parameters
- **roomId** (integer) - Required - The unique identifier for the chat room or resource.
#### Request Body
(Not applicable, authorization is based on session/authenticated user and path parameters)
### Request Example
```php
use App\Models\User;
Broadcast::channel('chat.{roomId}', function (User $user, int $roomId) {
// Check if the user is authorized to join the room
if ($user->canJoinRoom($roomId)) {
// Return user data if authorized
return ['id' => $user->id, 'name' => $user->name];
}
// Return false or null if not authorized
return false;
});
Response
Success Response (Conceptual 200 OK)
- id (integer) - The ID of the authorized user.
- name (string) - The name of the authorized user. (Additional user-specific data can be returned as defined by the application’s callback.)
Response Example
{
"id": 1,
"name": "John Doe"
}
Error Response (Conceptual 403 Forbidden)
Returns false or null if the user is not authorized to join the channel.
--------------------------------
### Define Laravel Command Options with Values and Defaults
Source: https://laravel.com/docs/12.x/artisan
Demonstrates how to define console command options that expect values, including how to set default values. It also shows how to invoke such commands from the shell, where a null value is assigned if the option is not provided without a default.
```php
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mail:send {user} {--queue=}';
php artisan mail:send 1 --queue=default
'mail:send {user} {--queue=default}'
Implement Assertions for Laravel Dusk Page Objects
Source: https://laravel.com/docs/12.x/dusk
Use the assert method in a Dusk Page object to verify that the browser is on the correct page. Assertions placed here, such as assertPathIs, run automatically upon navigating to the page, confirming the expected state.
/**
* Assert that the browser is on the page.
*/
public function assert(Browser $browser): void
{
$browser->assertPathIs($this->url());
}
Attach File with Custom Name and MIME Type in Laravel
Source: https://laravel.com/docs/12.x/mail
This example extends the basic file attachment by specifying a custom file name and MIME type for the attachment. The as() and withMime() methods are chained to the attachment.
/**
* Get the attachments for the message.
*
* @return array<int, \Illuminate\Mail\Mailables\Attachment>
*/
public function attachments(): array
{
return [
Attachment::fromStorage('/path/to/file')
->as('name.pdf')
->withMime('application/pdf'),
];
}
Laravel Zero-Configuration Dependency Resolution for Services
Source: https://laravel.com/docs/12.x/container
This PHP example showcases Laravel’s zero-configuration resolution, where a simple Service class is automatically resolved and injected into a route closure without explicit binding configuration. This simplifies dependency management for classes with no or only concrete dependencies.
<?php
class Service
{
// ...
}
Route::get('/', function (Service $service) {
dd($service::class);
});
Create Payment Intent with specific payment methods in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
Illustrates creating a Stripe payment intent using the payWith method, allowing specification of accepted payment methods (e.g., ‘card’, ‘bancontact’). The amount provided should be in the lowest currency denominator (e.g., cents for USD).
use Illuminate\Http\Request;
Route::post('/pay', function (Request $request) {
$payment = $request->user()->payWith(
$request->get('amount'), ['card', 'bancontact']
);
return $payment->client_secret;
});
Apply Middleware to Specific Resource/Singleton Controller Methods in Laravel PHP
Source: https://laravel.com/docs/12.x/controllers
This example illustrates how to use the middlewareFor method to apply middleware to one or more specific methods within a resource, API resource, singleton, or API singleton controller. It allows for precise control, enabling different middleware configurations for individual controller actions, and supports single or multiple middleware definitions.
Route::resource('users', UserController::class)
->middlewareFor('show', 'auth');
Route::apiResource('users', UserController::class)
->middlewareFor(['show', 'update'], 'auth');
Route::resource('users', UserController::class)
->middlewareFor('show', 'auth')
->middlewareFor('update', 'auth');
Route::apiResource('users', UserController::class)
->middlewareFor(['show', 'update'], ['auth', 'verified']);
Route::singleton('profile', ProfileController::class)
->middlewareFor('show', 'auth');
Route::apiSingleton('profile', ProfileController::class)
->middlewareFor(['show', 'update'], 'auth');
Include PHP Files in Envoy Setup
Source: https://laravel.com/docs/12.x/envoy
Includes an external PHP file, such as an autoloader, at the top of your Envoy.blade.php file. This enables access to external PHP classes and functions within the Envoy context, making complex setups easier to manage.
@include('vendor/autoload.php')
@task('restart-queues')
# ...
@endtask
Create New Laravel Cashier Subscription with Multiple Products
Source: https://laravel.com/docs/12.x/billing
This snippet shows how to create a new subscription that includes multiple billing products by passing an array of price IDs (e.g., ‘price_monthly’, ‘price_chat’) to the newSubscription method. This operation is typically performed within a Route handler.
use Illuminate\Http\Request;
Route::post('/user/subscribe', function (Request $request) {
$request->user()->newSubscription('default', [
'price_monthly',
'price_chat',
])->create($request->paymentMethodId);
// ...
});
Set Table Storage Engine for Laravel Migrations (MariaDB/MySQL)
Source: https://laravel.com/docs/12.x/migrations
This example illustrates how to specify the storage engine for a new table using the engine method within the table creation closure. It sets the engine to ‘InnoDB’, which is primarily applicable for MariaDB or MySQL databases.
Schema::create('users', function (Blueprint $table) {
$table->engine('InnoDB');
// ...
});
Remove Prefix from String with Str::chopStart()
Source: https://laravel.com/docs/12.x/strings
The Str::chopStart method removes the first occurrence of a given value from the beginning of a string, but only if the string actually starts with that value. It can also accept an array of potential prefixes, removing the first one that matches the start of the string. This is useful for cleaning up URLs or file paths by removing known leading segments.
use Illuminate\Support\Str;
$url = Str::chopStart('https://laravel.com', 'https://');
// 'laravel.com'
use Illuminate\Support\Str;
$url = Str::chopStart('http://laravel.com', ['https://', 'http://']);
// 'laravel.com'
GET /photos
Source: https://laravel.com/docs/12.x/controllers
Retrieve a list of all photo resources. This endpoint typically returns a collection of photo objects.
## GET /photos
### Description
Retrieve a list of all photo resources.
### Method
GET
### Endpoint
/photos
### Parameters
#### Path Parameters
_None_
#### Query Parameters
_None_
#### Request Body
_None_
### Request Example
{}
### Response
#### Success Response (200)
- **photos** (array) - An array of photo objects.
#### Response Example
[
{
"id": 1,
"title": "Photo 1",
"url": "/images/photo1.jpg"
},
{
"id": 2,
"title": "Photo 2",
"url": "/images/photo2.jpg"
}
]
GET /photos/{photo}
Source: https://laravel.com/docs/12.x/controllers
Retrieve a specific photo resource by its ID. This endpoint returns the details of a single photo.
## GET /photos/{photo}
### Description
Retrieve a specific photo resource by its ID.
### Method
GET
### Endpoint
/photos/{photo}
### Parameters
#### Path Parameters
- **photo** (integer) - Required - The ID of the photo to retrieve.
#### Query Parameters
_None_
#### Request Body
_None_
### Request Example
{}
### Response
#### Success Response (200)
- **id** (integer) - The unique identifier of the photo.
- **title** (string) - The title of the photo.
- **description** (string) - The description of the photo.
- **url** (string) - The URL to the photo image.
#### Response Example
{
"id": 1,
"title": "Photo 1",
"description": "A description for photo 1.",
"url": "/images/photo1.jpg"
}
Process Input Through Laravel Pipeline with Closures
Source: https://laravel.com/docs/12.x/helpers
This example shows how to use Laravel’s Pipeline facade to pass an input object through a series of closures. Each closure in the pipeline can inspect or modify the input and passes it to the next step via a $next callback, similar to HTTP middleware.
use Closure;
use AppModelsUser;
use IlluminateSupportFacadesPipeline;
$user = Pipeline::send($user)
->through([
function (User $user, Closure $next) {
// ...
return $next($user);
},
function (User $user, Closure $next) {
// ...
return $next($user);
},
])
->then(fn (User $user) => $user);
Adjust Argon2 Work Factor in Laravel
Source: https://laravel.com/docs/12.x/hashing
This PHP example demonstrates how to configure the work factor for the Argon2 hashing algorithm by providing memory, time, and threads options to the Hash::make method. These parameters allow fine-tuning the algorithm’s resource consumption and security level, as detailed in the official PHP documentation.
$hashed = Hash::make('password', [
'memory' => 1024,
'time' => 2,
'threads' => 2,
]);
Define a Basic Laravel GET Route with Closure (PHP)
Source: https://laravel.com/docs/12.x/routing
This snippet demonstrates the most fundamental way to define a GET route in Laravel, associating a URI with a simple closure function that returns a string. It illustrates expressive route definition without complex configuration.
use Illuminate\Support\Facades\Route;
Route::get('/greeting', function () {
return 'Hello World';
});
Define Laravel Command Options as Input Arrays
Source: https://laravel.com/docs/12.x/artisan
Illustrates how to define console command options that can accept multiple values using the * character. It provides an example of how to pass multiple instances of such an option when invoking the command from the shell.
'mail:send {--id=*}'
php artisan mail:send --id=1 --id=2
Laravel Prompts Password Input
Source: https://laravel.com/docs/12.x/prompts
Illustrates the basic usage of the password function in Laravel Prompts for sensitive input. It also shows how to add a placeholder and an informational hint to guide the user, masking the input as it’s typed.
use function Laravel\Prompts\password;
$password = password('What is your password?');
$password = password(
label: 'What is your password?',
placeholder: 'password',
hint: 'Minimum 8 characters.'
);
Integrate shadcn/ui Switch Component in React
Source: https://laravel.com/docs/12.x/starter-kits
This React JSX code snippet shows how to import and use a published shadcn/ui Switch component within a React functional component. It assumes the component has been successfully published to the specified path @/components/ui/switch.
import { Switch } from '@/components/ui/switch';
const MyPage = () => {
return (
<div>
<Switch />
</div>
);
};
export default MyPage;
Define Laravel Event with ShouldBroadcast Interface
Source: https://laravel.com/docs/12.x/broadcasting
This PHP snippet demonstrates how to define a Laravel event, OrderShipmentStatusUpdated, and mark it with the ShouldBroadcast interface. This interface signals Laravel to broadcast the event when it is fired, and the event class holds a public property for the Order instance.
<?php
namespace AppEvents;
use AppModelsOrder;
use IlluminateBroadcastingChannel;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateBroadcastingPresenceChannel;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateQueueSerializesModels;
class OrderShipmentStatusUpdated implements ShouldBroadcast
{
/**
* The order instance.
*
* @var \App\Models\Order
*/
public $order;
}
POST /user/confirmed-two-factor-authentication
Source: https://laravel.com/docs/12.x/fortify
Confirms the two-factor authentication setup by verifying a time-based one-time password (TOTP) code provided by the user. This finalizes the 2FA enablement.
## POST /user/confirmed-two-factor-authentication
### Description
Confirms the two-factor authentication setup by verifying a valid six-digit TOTP code provided by the user. If the code is correct, 2FA is fully enabled for the user.
### Method
POST
### Endpoint
/user/confirmed-two-factor-authentication
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **code** (string) - Required - The six-digit time-based one-time password (TOTP) from the user's authenticator app.
### Request Example
{
"code": "123456"
}
### Response
#### Success Response (200)
For XHR requests, a 200 HTTP response is returned. For standard requests, the user is redirected and the `status` session variable is set to `two-factor-authentication-confirmed`.
#### Response Example
{}
Set Custom Filename for Downloaded Invoice PDF
Source: https://laravel.com/docs/12.x/billing
Provide a custom filename for the downloaded invoice PDF by passing a string as the third argument to the ‘downloadInvoice’ method. The ‘.pdf’ extension will be automatically appended to the specified name.
return $request->user()->downloadInvoice($invoiceId, [], 'my-invoice');
Pass Data to Laravel View Using the with Method
Source: https://laravel.com/docs/12.x/views
This example shows how to use the with method to incrementally add individual pieces of data to a Laravel view. This approach allows chaining multiple data assignments before returning the view instance, providing a more fluent interface.
return view('greeting')
->with('name', 'Victoria')
->with('occupation', 'Astronaut');
Generate Laravel API Resource Controller
Source: https://laravel.com/docs/12.x/controllers
Creates a resource controller that is optimized for API usage, automatically excluding the create and edit methods. This command simplifies the setup for API-focused controllers.
php artisan make:controller PhotoController --api
Swap Subscription Price Without Proration (PHP)
Source: https://laravel.com/docs/12.x/billing
Demonstrates how to change a subscription’s price without applying proration to the charges. The noProrate method is chained before the swap method to prevent automatic proration by Stripe.
$user->subscription('default')->noProrate()->swap('price_yearly');
Configure Laravel Prompts multiselect with default choices and hint
Source: https://laravel.com/docs/12.x/prompts
Shows how to pre-select multiple options and provide a hint message for the multiselect function. The default parameter accepts an array of options to be initially selected, and hint offers user guidance, enhancing the prompt’s usability.
use function Laravel\Prompts\multiselect;
$permissions = multiselect(
label: 'What permissions should be assigned?',
options: ['Read', 'Create', 'Update', 'Delete'],
default: ['Read', 'Create'],
hint: 'Permissions may be updated at any time.'
);
Make a Simple Charge without an Authenticated User (PHP)
Source: https://laravel.com/docs/12.x/billing
Explains how to perform a one-time charge when there isn’t an authenticated user tied to the request. This is achieved by creating a new instance of the billable model (e.g., App\Models\User) and invoking the charge method on it.
use App\Models\User;
$stripeCharge = (new User)->charge(100, $paymentMethod);
Debug Laravel Query Bindings and SQL with dd and dump
Source: https://laravel.com/docs/12.x/queries
These examples show how to use Laravel’s dd() and dump() methods directly on a query builder for debugging. dd() (dump and die) will display the query’s bindings and SQL, then terminate the script. dump() will display the same information but allow the script to continue execution.
DB::table('users')->where('votes', '>', 100)->dd();
DB::table('users')->where('votes', '>', 100)->dump();
Resume Laravel Cashier Subscription (PHP)
Source: https://laravel.com/docs/12.x/billing
Reactivate a canceled subscription if the customer is still within their grace period. Upon resumption, the customer will not be billed immediately but will continue on their original billing cycle.
$user->subscription('default')->resume();
Retrieve all payment methods for a user (Laravel Cashier)
Source: https://laravel.com/docs/12.x/billing
This PHP code demonstrates how to retrieve all payment methods associated with a billable model (e.g., a user) using Laravel Cashier’s paymentMethods() method. It returns a collection of Laravel\Cashier\PaymentMethod instances.
$paymentMethods = $user->paymentMethods();
Assert text is present on page in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the given text is present on the page. This checks for the appearance of a specific string anywhere in the rendered HTML.
$browser->assertSee($text);
Enable Vite Manifest SRI Plugin in vite.config.js
Source: https://laravel.com/docs/12.x/vite
After installing vite-plugin-manifest-sri, this JavaScript configuration shows how to import and enable the plugin within your vite.config.js file. This allows Vite to generate integrity hashes in its manifest for your assets.
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import manifestSRI from 'vite-plugin-manifest-sri'; // [tl! add]
export default defineConfig({
plugins: [
laravel({
// ...
}),
manifestSRI(), // [tl! add]
],
});
Find Laravel Cashier Promotion Code by Customer-Facing Code
Source: https://laravel.com/docs/12.x/billing
This PHP snippet illustrates how to retrieve a PromotionCode object using its customer-facing code with Laravel Cashier. It demonstrates both finding any promotion code and specifically finding an active one, returning an instance of Laravel\Cashier\PromotionCode.
// Find a promotion code ID by its customer facing code...
$promotionCode = $user->findPromotionCode('SUMMERSALE');
// Find an active promotion code ID by its customer facing code...
$promotionCode = $user->findActivePromotionCode('SUMMERSALE');
Fake Specific Laravel Processes with Custom Results
Source: https://laravel.com/docs/12.x/processes
This PHP example demonstrates faking specific commands by mapping command patterns to custom results using Process::result(). Wildcards (*) can be used in command patterns to match multiple similar commands, allowing fine-grained control over faked process behavior, including output, error output, and exit code for each matched process.
Process::fake([
'cat *' => Process::result(
output: 'Test "cat" output',
),
'ls *' => Process::result(
output: 'Test "ls" output',
),
]);
Retrieve Stripe Customer by ID using Cashier
Source: https://laravel.com/docs/12.x/billing
Demonstrates how to fetch a billable model instance (e.g., a User) from the database using its Stripe customer ID. The Cashier::findBillable method returns the corresponding model if found.
use Laravel\Cashier\Cashier;
$user = Cashier::findBillable($stripeId);
Obtain Cache Instance via Laravel Cache Facade (PHP)
Source: https://laravel.com/docs/12.x/cache
This PHP example demonstrates how to use the Cache facade within a Laravel controller to retrieve a value from the default cache store. It showcases the basic usage of Cache::get() for fetching data.
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Cache;
class UserController extends Controller
{
/**
* Show a list of all users of the application.
*/
public function index(): array
{
$value = Cache::get('key');
return [
// ...
];
}
}
Assert URL path is not exact in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the current path does not match the given path. This assertion verifies that the URL’s path is not a specific value.
$browser->assertPathIsNot('/home');
Create a Compound Index (Laravel PHP)
Source: https://laravel.com/docs/12.x/migrations
This PHP example demonstrates how to create a compound (or composite) index using Laravel’s schema builder. An array of column names, such as ‘account_id’ and ‘created_at’, is passed to the index method to define the multi-column index.
$table->index(['account_id', 'created_at']);
Laravel Dusk: Selecting multiple options from a dropdown
Source: https://laravel.com/docs/12.x/dusk
For <select> elements that allow multiple selections, you can pass an array of values to the select method. This will check all specified options within the dropdown.
$browser->select('categories', ['Art', 'Music']);
Configure Fortify Features in ‘fortify.php’
Source: https://laravel.com/docs/12.x/fortify
This PHP configuration array, located in ‘config/fortify.php’, allows you to specify which authentication features, such as user registration, password reset, and email verification, Fortify should enable and expose.
'features' => [
Features::registration(),
Features::resetPasswords(),
Features::emailVerification(),
],
Retrieve Paddle price previews in PHP
Source: https://laravel.com/docs/12.x/cashier-paddle
This snippet demonstrates how to fetch a list of price previews for given price IDs using Laravel Cashier’s previewPrices method. The currency is determined by the request’s IP address. It returns a collection of price objects.
use Laravel\Paddle\Cashier;
$prices = Cashier::previewPrices(['pri_123', 'pri_456']);
GET /user/two-factor-qr-code
Source: https://laravel.com/docs/12.x/fortify
Retrieves the SVG representation of the QR code needed for users to scan into their authenticator applications. This endpoint is typically used by JavaScript-powered frontends.
## GET /user/two-factor-qr-code
### Description
Retrieves the QR code as an SVG string for the authenticated user's two-factor authentication setup. The QR code should be displayed for the user to scan with a TOTP compatible mobile authentication application.
### Method
GET
### Endpoint
/user/two-factor-qr-code
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
No request body for GET requests.
### Response
#### Success Response (200)
A JSON object containing the SVG string of the QR code.
#### Response Example
{
"svg": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 240 240\"><!-- QR code SVG content --></svg>"
}
Invoice Multiple Items using Tab Price (PHP)
Source: https://laravel.com/docs/12.x/billing
Explains how to add multiple items to a customer’s ‘tab’ using the tabPrice method before generating a single invoice for all accumulated items. This is suitable for scenarios where a customer purchases several different products.
$user->tabPrice('price_tshirt', 5);
$user->tabPrice('price_mug', 2);
$user->invoice();
Define a Blade Macro for Vite Asset Aliases in Laravel
Source: https://laravel.com/docs/12.x/vite
Create a custom macro on the Illuminate\Support\Facades\Vite class within a service provider’s boot method. This allows defining aliases for commonly referenced asset directories, simplifying asset paths in Blade templates.
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Vite::macro('image', fn (string $asset) => $this->asset("resources/images/{$asset}"));
}
Assert current URL port is not in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the current URL port does not match the given port. This assertion ensures that the browser is not on a specific port.
$browser->assertPortIsNot($port);
Showing a Loading Spinner for Asynchronous Tasks in Laravel Prompts (PHP)
Source: https://laravel.com/docs/12.x/prompts
This example demonstrates using the spin function in Laravel Prompts to display an animated spinner and a message while an asynchronous callback executes. It indicates ongoing processes and returns the callback’s result upon completion.
use function Laravel\Prompts\spin;
$response = spin(
callback: fn () => Http::get('http://example.com'),
message: 'Fetching response...'
);
Configure Custom Billable Model for Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP snippet shows how to instruct Cashier to use a custom billable model instead of the default App\Models\User. It should be placed in the boot method of your AppServiceProvider to register the custom model with Cashier.
use App\Models\Cashier\User;
use Laravel\Cashier\Cashier;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Cashier::useCustomerModel(User::class);
}
Assert URL host equality in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
Confirm that the host part of the current URL matches the given host string. This is vital for testing applications across different subdomains or environments.
$browser->assertHostIs($host);
Swap Subscription Plan, No Proration, and Invoice Immediately in Laravel Cashier Paddle
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP snippet combines disabling proration with immediate invoicing when swapping a user’s subscription plan. It chains noProrate with swapAndInvoice.
$user->subscription('default')->noProrate()->swapAndInvoice($premium = 'pri_456');
Enable Asset Prefetching Without Concurrency Limit
Source: https://laravel.com/docs/12.x/vite
Configure Laravel’s Vite integration to prefetch all application assets without a concurrency limit on initial page load. This can be useful when all assets should be downloaded simultaneously.
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Vite::prefetch();
}
Install Libraries for PSR-7 Request Compatibility
Source: https://laravel.com/docs/12.x/requests
To enable PSR-7 compatibility for HTTP requests and responses in Laravel, install the necessary Symfony HTTP Message Bridge and Nyholm PSR-7 libraries using Composer. These packages facilitate conversion between Laravel’s native request/response objects and PSR-7 compliant implementations.
composer require symfony/psr-http-message-bridge
composer require nyholm/psr7
Execute Redis Commands with Laravel Facade command Method
Source: https://laravel.com/docs/12.x/redis
This PHP snippet demonstrates an alternative way to execute Redis commands using the Redis facade’s command method. This method accepts the Redis command name as its first argument and an array of arguments as its second, providing a more explicit way to interact with Redis when dynamic method calls are not preferred or clear. Here, it retrieves a range from a list.
$values = Redis::command('lrange', ['name', 5, 10]);
Take Screenshots in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This PHP code demonstrates various methods for capturing screenshots during Laravel Dusk tests. The screenshot method takes a full-page screenshot, responsiveScreenshots captures multiple screenshots at different breakpoints, and screenshotElement targets a specific HTML element.
$browser->screenshot('filename');
$browser->responsiveScreenshots('filename');
$browser->screenshotElement('#selector', 'filename');
GET /oauth/authorize
Source: https://laravel.com/docs/12.x/passport
Initiates the authorization code grant flow by redirecting the user to the authorization server to approve the client application’s request.
## GET /oauth/authorize
### Description
Initiates the authorization code grant flow by redirecting the user to the authorization server. The user will be prompted to approve the client application's request for access to their resources.
### Method
GET
### Endpoint
/oauth/authorize
### Parameters
#### Query Parameters
- **client_id** (string) - Required - The client ID of the consuming application.
- **redirect_uri** (string) - Required - The URL where the user will be redirected after authorization. Must match a registered redirect URI for the client.
- **response_type** (string) - Required - Must be 'code' for authorization code grant.
- **scope** (string) - Optional - A space-separated list of scopes the client is requesting.
- **state** (string) - Required - An opaque value used to maintain state between the request and callback. Used to prevent CSRF attacks.
- **prompt** (string) - Optional - Specifies the authentication behavior. Can be 'none' (throws error if not authenticated), 'consent' (always displays approval screen), or 'login' (always prompts re-login). If not provided, prompts only if not previously authorized.
### Request Example
N/A (This is a redirect, not a direct API call with a request body)
### Response
#### Success Response (302 Redirect)
Upon successful authorization (or if `prompt=none` and already authorized), the user is redirected to the `redirect_uri` with an authorization `code` and the `state` parameter appended as query parameters.
#### Response Example
https://third-party-app.com/callback?code=AUTH_CODE_HERE&state=RANDOM_STATE_HERE
GET /user/two-factor-recovery-codes
Source: https://laravel.com/docs/12.x/fortify
Retrieves the list of two-factor authentication recovery codes for the authenticated user. These codes allow users to log in if they lose access to their primary authenticator device.
## GET /user/two-factor-recovery-codes
### Description
Retrieves the current list of two-factor authentication recovery codes for the authenticated user. These codes can be used for emergency login.
### Method
GET
### Endpoint
/user/two-factor-recovery-codes
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
No request body for GET requests.
### Response
#### Success Response (200)
A JSON array containing the user's recovery codes.
#### Response Example
[
"ABCDEFGHIJ",
"KLMNOPQRST",
"UVWXYZABCD",
"EFGHIJKLMN",
"OPQRSTUVWX"
]
Use Short Attribute Syntax for Blade Components
Source: https://laravel.com/docs/12.x/blade
This example illustrates the ‘short attribute’ syntax in Blade components, which allows you to pass variables to component attributes using a concise :variableName notation. It also shows the equivalent expanded syntax for clarity.
{{-- Short attribute syntax... --}}
<x-profile :$userId :$name />
{{-- Is equivalent to... --}}
<x-profile :user-id="$userId" :name="$name" />
Laravel Dusk: Retrieving an element’s display text
Source: https://laravel.com/docs/12.x/dusk
This code illustrates how to fetch the visible display text of an HTML element. The text method takes a selector (CSS or Dusk) and returns the textual content within that element.
$text = $browser->text('selector');
Trigger Custom Prefetch Event Using JavaScript
Source: https://laravel.com/docs/12.x/vite
Demonstrates how to manually dispatch a custom event on the window object using JavaScript. This event can be configured in Laravel to initiate asset prefetching at a specific time or condition, such as after a delay.
<script>
addEventListener('load', () =>
setTimeout(() => {
dispatchEvent(new Event('vite:prefetch'));
}, 3000),
);
</script>
Prompt for User Input with Auto-completion (Laravel PHP)
Source: https://laravel.com/docs/12.x/prompts
Demonstrates the basic usage of the suggest function to prompt the user for input while providing a static list of auto-completion choices. The user can still enter any value, regardless of the suggestions.
use function Laravel\Prompts\suggest;
$name = suggest('What is your name?', ['Taylor', 'Dayle']);
Configure Connection and Queue for Laravel Job Batch (PHP)
Source: https://laravel.com/docs/12.x/queues
This example illustrates how to specify the queue connection and queue name for all jobs within a Laravel batch using the onConnection and onQueue methods. All jobs in a batch must use the same connection and queue.
$batch = Bus::batch([
// ...
])->then(function (Batch $batch) {
// All jobs completed successfully...
})->onConnection('redis')->onQueue('imports')->dispatch();
Create a basic Laravel Folio page
Source: https://laravel.com/docs/12.x/folio
This snippet demonstrates how to create a simple Laravel Folio page. By placing a greeting.blade.php file in the resources/views/pages directory, it becomes automatically accessible at the /greeting URL.
<div>
Hello World
</div>
Configure RateLimited Middleware with Release Delay in Laravel
Source: https://laravel.com/docs/12.x/queues
This PHP snippet shows how to use the releaseAfter method with the RateLimited middleware to specify a custom delay before a rate-limited job is re-attempted. In this example, the job will be attempted again after 60 seconds.
/**
* Get the middleware the job should pass through.
*
* @return array<int, object>
*/
public function middleware(): array
{
return [(new RateLimited('backups'))->releaseAfter(60)];
}
Create Stripe Checkout Session with Order Metadata (PHP/Laravel)
Source: https://laravel.com/docs/12.x/billing
This code snippet demonstrates how to create a Stripe Checkout session, associating it with an application-specific ‘Order’ model. It passes the ‘order_id’ as metadata to Stripe and configures success/cancel URLs, using Laravel’s routing and Cashier’s checkout method.
use App\Models\Cart;
use App\Models\Order;
use Illuminate\Http\Request;
Route::get('/cart/{cart}/checkout', function (Request $request, Cart $cart) {
$order = Order::create(
[
'cart_id' => $cart->id,
'price_ids' => $cart->price_ids,
'status' => 'incomplete',
]
);
return $request->user()->checkout($order->price_ids, [
'success_url' => route('checkout-success').'?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => route('checkout-cancel'),
'metadata' => ['order_id' => $order->id],
]);
})->name('checkout');
Access Laravel Package Translation Line
Source: https://laravel.com/docs/12.x/packages
This PHP example shows how to retrieve a specific translation line from a namespaced package using the trans() helper function. The syntax package::file.line (e.g., courier::messages.welcome) is used to specify the package, file, and key for the desired translation.
echo trans('courier::messages.welcome');
Create Basic JSON Array Response in Laravel
Source: https://laravel.com/docs/12.x/responses
This example shows how to return an array from a Laravel route closure. Laravel automatically converts the array into a JSON HTTP response, simplifying API development.
Route::get('/', function () {
return [1, 2, 3];
});
Attach Multiple Headers to Laravel Response Fluently
Source: https://laravel.com/docs/12.x/responses
This example shows how to fluently chain header methods to add multiple HTTP headers to a response instance in Laravel. It allows for granular control over individual header values.
return response($content)
->header('Content-Type', $type)
->header('X-Header-One', 'Header Value')
->header('X-Header-Two', 'Header Value');
Define Database Connections for Truncation (PHP)
Source: https://laravel.com/docs/12.x/dusk
Configure the $connectionsToTruncate property in your test class to specify which database connections should have their tables truncated. This is useful in applications with multiple database connections, allowing you to target specific ones for testing.
/**
* Indicates which connections should have their tables truncated.
*
* @var array
*/
protected $connectionsToTruncate = ['mysql'];
Define and submit an Inertia form with Precognition (Vue 3 Script Setup)
Source: https://laravel.com/docs/12.x/precognition
This Vue 3 script setup block demonstrates defining a form using useForm from laravel-precognition-vue-inertia. It configures a POST request to /users with initial data, and defines a submit function that handles successful submission by resetting the form and preserving scroll.
<script setup>
import { useForm } from 'laravel-precognition-vue-inertia';
const form = useForm('post', '/users', {
name: '',
email: '',
});
const submit = () =>
form.submit({
preserveScroll: true,
onSuccess: () => form.reset(),
});
</script>
Laravel Text: Default Validation Error Message Example
Source: https://laravel.com/docs/12.x/validation
This example shows a default Laravel validation error message before any customization. It demonstrates how placeholders like :value are used directly in the output without specific mappings.
The credit card number field is required when payment type is cc.
Laravel Text: Customized Validation Error Message Example
Source: https://laravel.com/docs/12.x/validation
This example shows a Laravel validation error message after customizing the value representation. It demonstrates how a user-defined mapping for :value improves the readability and user-friendliness of the error.
The credit card number field is required when payment type is credit card.
Create Multiple Distinct Subscriptions for a User in Laravel
Source: https://laravel.com/docs/12.x/cashier-paddle
Illustrates how to allow a user to have multiple concurrent subscriptions by specifying a unique ‘type’ argument to the subscribe method. This enables managing separate billing cycles and products for different services.
use Illuminate\Http\Request;
Route::post('/swimming/subscribe', function (Request $request) {
$checkout = $request->user()->subscribe($swimmingMonthly = 'pri_123', 'swimming');
return view('billing', ['checkout' => $checkout]);
});
Apply Laravel Sanctum ‘abilities’ Middleware to Require All Permissions
Source: https://laravel.com/docs/12.x/sanctum
This example demonstrates how to protect a route using the abilities middleware, ensuring that the authenticating API token possesses all of the specified abilities. The route is also protected by the auth:sanctum guard. If the token lacks any of the required abilities, the request will be unauthorized.
Route::get('/orders', function () {
// Token has both "check-status" and "place-orders" abilities...
})->middleware(['auth:sanctum', 'abilities:check-status,place-orders']);
Customize Algolia search engine behavior in Laravel Scout using a closure
Source: https://laravel.com/docs/12.x/scout
This PHP example shows how to pass a closure to the search method for advanced customization of the search engine’s behavior. The closure receives the search engine instance, query, and options, allowing modification (e.g., adding geo-location data) before the query is executed. This specific example adds a geo-distance filter for Algolia.
use Algolia\AlgoliaSearch\SearchIndex;
use App\Models\Order;
Order::search(
'Star Trek',
function (SearchIndex $algolia, string $query, array $options) {
$options['body']['query']['bool']['filter']['geo_distance'] = [
'distance' => '1000km',
'location' => ['lat' => 36, 'lon' => 111],
];
return $algolia->search($query, $options);
}
)->get();
Configure Nginx for Laravel Deployment
Source: https://laravel.com/docs/12.x/deployment
Provides a starting Nginx server block configuration for deploying a Laravel application. It directs all requests to public/index.php, sets headers, and handles PHP processing via fastcgi_pass to PHP-FPM, ensuring sensitive files are protected.
server {
listen 80;
listen [::]:80;
server_name example.com;
root /srv/example.com/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
index index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ ^/index\.php(/|$) {
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_hide_header X-Powered-By;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
Get Laravel session data with default or closure values
Source: https://laravel.com/docs/12.x/session
This PHP snippet shows how to retrieve session data using the get() method, providing a fallback. It illustrates passing a default string value or a closure, which will be executed and its result returned if the specified key does not exist in the session.
$value = $request->session()->get('key', 'default');
$value = $request->session()->get('key', function () {
return 'default';
});
Drop all tables and migrate in Laravel with Artisan
Source: https://laravel.com/docs/12.x/migrations
Explains how to use the ‘migrate:fresh’ Artisan command to drop all tables from the database and then re-run migrations. This command can also run database seeds or target a specific database connection, but should be used with caution as it drops all tables regardless of prefix.
php artisan migrate:fresh
php artisan migrate:fresh --seed
php artisan migrate:fresh --database=admin
Charge One-Time Prices to a Subscription (PHP)
Source: https://laravel.com/docs/12.x/cashier-paddle
Allows adding one-time charges to a subscriber’s existing subscription. The charge method schedules the charge for the next billing interval, while chargeAndInvoice processes it immediately.
// Charge a single price...
$response = $user->subscription()->charge('pri_123');
// Charge multiple prices at once...
$response = $user->subscription()->charge(['pri_123', 'pri_456']);
$response = $user->subscription()->chargeAndInvoice('pri_123');
Retrieve Customer’s Current Balance
Source: https://laravel.com/docs/12.x/billing
Fetches the current balance for a billable customer. The balance() method returns a formatted string representing the amount the customer currently owes or is owed, in their respective currency.
$balance = $user->balance();
Retrieve upcoming invoice for a specific subscription in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
Retrieves the next pending invoice for a particular subscription of a customer. This is done by chaining the upcomingInvoice method to a specific subscription instance.
$invoice = $user->subscription('default')->upcomingInvoice();
Set Specific Laravel Cashier Subscription Quantity
Source: https://laravel.com/docs/12.x/billing
This snippet illustrates how to directly set a subscription’s quantity to a specific value using the updateQuantity method for a user’s default subscription.
$user->subscription('default')->updateQuantity(10);
Create or Retrieve Stripe Customer for Billable Model
Source: https://laravel.com/docs/12.x/billing
Provides a convenient method to either retrieve an existing Stripe customer or create a new one if it doesn’t already exist for the given billable model. This ensures a Stripe customer record is always available.
$stripeCustomer = $user->createOrGetStripeCustomer();
Enter Laravel Tinker REPL Environment
Source: https://laravel.com/docs/12.x/artisan
Execute this Artisan command to enter the Laravel Tinker environment. Tinker provides an interactive REPL (Read-Eval-Print Loop) where you can interact with your Laravel application’s models, jobs, events, and other components directly from the command line.
php artisan tinker
GET /photos/{photo}/edit
Source: https://laravel.com/docs/12.x/controllers
Display the form for editing the specified photo resource. This endpoint typically returns an HTML view.
## GET /photos/{photo}/edit
### Description
Display the form for editing the specified photo resource.
### Method
GET
### Endpoint
/photos/{photo}/edit
### Parameters
#### Path Parameters
- **photo** (integer) - Required - The ID of the photo to edit.
#### Query Parameters
_None_
#### Request Body
_None_
### Request Example
{}
### Response
#### Success Response (200)
- **html_form** (string) - HTML content for the resource editing form.
#### Response Example
"<!DOCTYPE html>\n<html>\n <head>\n <title>Edit Photo</title>\n </head>\n <body>\n <h1>Edit Photo</h1>\n <form action=\"/photos/1\" method=\"POST\">\n <input type=\"hidden\" name=\"_method\" value=\"PUT\">\n <label for=\"title\">Title:</label>\n <input type=\"text\" id=\"title\" name=\"title\" value=\"Photo 1\"><br>\n <input type=\"submit\" value=\"Update\"><br>\n </form>\n </body>\n</html>"
Example Usage: Merging Default Classes in Laravel Blade
Source: https://laravel.com/docs/12.x/blade
This component usage demonstrates how default classes (‘alert’, ‘alert-$type’) are merged with an explicitly provided class (‘mb-4’) when rendering the component.
<x-alert type="error" :message="$message" class="mb-4"/>
Assert text is not present on page in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the given text is not present on the page. This verifies that a specific string does not appear in the rendered HTML.
$browser->assertDontSee($text);
Generate a new Laravel Dusk component using Artisan
Source: https://laravel.com/docs/12.x/dusk
This command generates a new Dusk component class within the tests/Browser/Components directory. It’s the first step to creating reusable UI testing logic for elements like a date picker, centralizing interaction patterns.
php artisan dusk:component DatePicker
Compare Offset and Cursor Pagination SQL Queries
Source: https://laravel.com/docs/12.x/pagination
This SQL example illustrates the fundamental difference between offset and cursor pagination. Offset pagination uses OFFSET to skip records, which can be inefficient for large datasets, while cursor pagination uses WHERE clauses based on column values to efficiently fetch the next set of records, improving performance for large tables.
# Offset Pagination...
select * from users order by id asc limit 15 offset 15;
# Cursor Pagination...
select * from users where id > 15 order by id asc limit 15;
Prompt for User Input with Laravel ask Method
Source: https://laravel.com/docs/12.x/artisan
The ask method prompts the user with a question and returns their input. It can also accept an optional second argument which specifies a default value that should be returned if no user input is provided.
/**
* Execute the console command.
*/
public function handle(): void
{
$name = $this->ask('What is your name?');
// ...
}
$name = $this->ask('What is your name?', 'Taylor');
Return an Eloquent Resource using toResource Helper (PHP)
Source: https://laravel.com/docs/12.x/eloquent-resources
This PHP example shows a convenient way to return an Eloquent resource by calling the toResource() method on an Eloquent model instance. Laravel automatically discovers the corresponding resource class based on naming conventions (e.g., User model maps to UserResource).
return User::findOrFail($id)->toResource();
Schedule a Queued Job in Laravel PHP
Source: https://laravel.com/docs/12.x/scheduling
Demonstrates how to schedule a Laravel queued job using the Schedule::job method. This example schedules the App\Jobs\Heartbeat job to run every five minutes.
use App\Jobs\Heartbeat;
use Illuminate\Support\Facades\Schedule;
Schedule::job(new Heartbeat)->everyFiveMinutes();
Assign Multiple Middleware to a Laravel Route
Source: https://laravel.com/docs/12.x/middleware
This example demonstrates applying multiple middleware simultaneously to a single route in Laravel. By passing an array of middleware class names to the middleware method, all listed middleware, such as First and Second, will be executed in order for requests hitting the / route.
Route::get('/', function () {
// ...
})->middleware([First::class, Second::class]);
Install Laravel Vonage Notification Channel and Guzzle
Source: https://laravel.com/docs/12.x/notifications
Before sending SMS notifications via Vonage in Laravel, install the necessary packages using Composer. This command adds laravel/vonage-notification-channel for Vonage integration and guzzlehttp/guzzle as an HTTP client dependency. These packages are essential for enabling SMS functionality in your application.
composer require laravel/vonage-notification-channel guzzlehttp/guzzle
Accept JavaScript Dialog in Laravel Dusk PHP
Source: https://laravel.com/docs/12.x/dusk
This PHP code shows how to accept (click ‘OK’ on) an open JavaScript dialog using Laravel Dusk. The acceptDialog method closes the dialog positively, continuing the test flow as if the user clicked OK.
$browser->acceptDialog();
Use helper methods for common route parameter constraints in Laravel
Source: https://laravel.com/docs/12.x/routing
This example illustrates the use of convenient helper methods like whereNumber(), whereAlpha(), whereAlphaNumeric(), whereUuid(), whereUlid(), and whereIn() to quickly add predefined pattern constraints to route parameters, simplifying common validation tasks.
Route::get('/user/{id}/{name}', function (string $id, string $name) {
// ...
})->whereNumber('id')->whereAlpha('name');
Route::get('/user/{name}', function (string $name) {
// ...
})->whereAlphaNumeric('name');
Route::get('/user/{id}', function (string $id) {
// ...
})->whereUuid('id');
Route::get('/user/{id}', function (string $id) {
// ...
})->whereUlid('id');
Route::get('/category/{category}', function (string $category) {
// ...
})->whereIn('category', ['movie', 'song', 'painting']);
Route::get('/category/{category}', function (string $category) {
// ...
})->whereIn('category', CategoryEnum::cases());
Invoke Laravel MCP Prompts and Resources
Source: https://laravel.com/docs/12.x/mcp
This snippet shows the basic syntax for invoking prompts and resources on a Laravel MCP server within a test case. It illustrates how to call the prompt and resource methods on the server instance.
$response = WeatherServer::prompt(...);
$response = WeatherServer::resource(...);
Calculate Aggregate Values with Laravel Query Builder
Source: https://laravel.com/docs/12.x/queries
This PHP example demonstrates how to use aggregate methods like count and max directly on the DB facade. It shows retrieving the total number of users and the maximum price from orders.
use Illuminate\Support\Facades\DB;
$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
Get Value of a Specific Blade Component Attribute
Source: https://laravel.com/docs/12.x/blade
This snippet uses the get method to retrieve the value of a single, specified attribute from the component’s attribute bag. It provides direct access to an attribute’s content.
{{ $attributes->get('class') }}
Define Pluralization Rules in Laravel Translation Files (PHP, JSON)
Source: https://laravel.com/docs/12.x/localization
These examples illustrate how to define basic singular and plural forms for translation strings. In PHP language files, you separate forms with a pipe | character. The JSON example shows how to apply the same | delimiter when translation strings are used as keys in JSON language files, allowing Laravel to pick the correct form based on count.
'apples' => 'There is one apple|There are many apples',
{
"There is one apple|There are many apples": "Hay una manzana|Hay muchas manzanas"
}
Extend Default Cashier Subscription Model
Source: https://laravel.com/docs/12.x/cashier-paddle
Customize Cashier’s internal models by defining your own model, like Subscription, and extending Laravel\Paddle\Subscription to add bespoke functionalities or override behavior.
use Laravel\Paddle\Subscription as CashierSubscription;
class Subscription extends CashierSubscription
{
// ...
}
Conditionally Queue Laravel Event Listener
Source: https://laravel.com/docs/12.x/events
This example demonstrates how to conditionally queue a Laravel event listener by implementing the shouldQueue method. This method allows you to determine whether the listener should be queued at runtime based on specific conditions, such as event data.
<?php
namespace App\Listeners;
use App\Events\OrderCreated;
use Illuminate\Contracts\Queue\ShouldQueue;
class RewardGiftCard implements ShouldQueue
{
/**
* Reward a gift card to the customer.
*/
public function handle(OrderCreated $event): void
{
// ...
}
/**
* Determine whether the listener should be queued.
*/
public function shouldQueue(OrderCreated $event): bool
{
return $event->order->subtotal >= 5000;
}
}
Manually control and advance progress bar in Laravel Prompts
Source: https://laravel.com/docs/12.x/prompts
For scenarios requiring explicit control, this snippet illustrates how to initialize a progress bar with a total number of steps and manually advance it using advance(). The start() and finish() methods are used to begin and end the progress display, giving full control over the progress flow.
$progress = progress(label: 'Updating users', steps: 10);
$users = User::all();
$progress->start();
foreach ($users as $user) {
$this->performTask($user);
$progress->advance();
}
$progress->finish();
Press Button by Text or Selector using Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
The press method clicks a button element on the page. The button can be identified by its display text or a CSS/Dusk selector.
$browser->press('Login');
Connect to Laravel Database CLI
Source: https://laravel.com/docs/12.x/database
Connects to the default database’s command-line interface using the Artisan db command. This provides direct access to the database shell for interactive operations.
php artisan db
Generate a new basic controller using Artisan
Source: https://laravel.com/docs/12.x/controllers
This Artisan command creates a new controller class with a default structure in the app/Http/Controllers directory. It’s the standard way to set up a new controller for your application.
php artisan make:controller UserController
Publish Laravel Horizon Assets
Source: https://laravel.com/docs/12.x/horizon
After installing the Horizon package, this Artisan command publishes Horizon’s front-end assets (JavaScript, CSS, etc.) and its configuration file to your application. This makes the Horizon dashboard available and allows customization of its settings.
php artisan horizon:install
Get Primary Keys of Eloquent Collection Models (PHP)
Source: https://laravel.com/docs/12.x/eloquent-collections
The modelKeys method returns an array containing the primary keys for all Eloquent models currently present in the collection. This is useful for quickly getting a list of identifiers for the models.
$users->modelKeys();
// [1, 2, 3, 4, 5]
Initiate Paddle Checkout Session in Laravel
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP snippet demonstrates how to initiate a Paddle checkout session for a specific price plan using Laravel’s Cashier. It returns a view with the checkout object, allowing the user to subscribe by clicking a button that will invoke the Paddle Checkout Overlay.
use Illuminate\Http\Request;
Route::get('/subscribe', function (Request $request) {
$checkout = $request->user()->checkout('price_basic_monthly')
->returnTo(route('dashboard'));
return view('subscribe', ['checkout' => $checkout]);
})->name('subscribe');
Define a route to a basic controller method in Laravel
Source: https://laravel.com/docs/12.x/controllers
This code snippet illustrates how to register a GET route that directs to a specific method (show) within a controller (UserController). Laravel automatically maps URL parameters to the controller method’s arguments.
use App\Http\Controllers\UserController;
Route::get('/user/{id}', [UserController::class, 'show']);
Assert query string parameter is missing in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the given query string parameter is missing. This ensures a specific parameter is not present in the URL’s query string.
$browser->assertQueryStringMissing($name);
Define Route for Downloading Paddle Invoice PDF (PHP Laravel)
Source: https://laravel.com/docs/12.x/cashier-paddle
This Laravel route definition handles requests for downloading an invoice PDF for a given transaction ID. It leverages the redirectToInvoicePdf() method available on the Laravel\Paddle\Transaction model to serve the invoice document directly.
use Illuminate\Http\Request;
use Laravel\Paddle\Transaction;
Route::get('/download-invoice/{transaction}', function (Request $request, Transaction $transaction) {
return $transaction->redirectToInvoicePdf();
})->name('download-invoice');
Configure Vite for Vue.js in Laravel
Source: https://laravel.com/docs/12.x/vite
This vite.config.js setup integrates the Vue plugin, enabling Vue.js support within a Laravel project. It includes specific transformAssetUrls options crucial for correctly handling asset paths in Vue Single File Components, ensuring they resolve through the Vite server.
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [
laravel(['resources/js/app.js']),
vue({
template: {
transformAssetUrls: {
// The Vue plugin will re-write asset URLs, when referenced
// in Single File Components, to point to the Laravel web
// server. Setting this to `null` allows the Laravel plugin
// to instead re-write asset URLs to point to the Vite
// server instead.
base: null,
// The Vue plugin will parse absolute URLs and treat them
// as absolute paths to files on disk. Setting this to
// `false` will leave absolute URLs un-touched so they can
// reference assets in the public directory as expected.
includeAbsolute: false,
},
},
}),
],
});
Dispatch a Laravel event in PHP
Source: https://laravel.com/docs/12.x/broadcasting
This PHP snippet demonstrates how to dispatch a custom Laravel event, OrderShipmentStatusUpdated, passing an $order object as an argument. Dispatched events can trigger listeners, including those configured for broadcasting to client-side applications.
use App\Events\OrderShipmentStatusUpdated;
OrderShipmentStatusUpdated::dispatch($order);
Registering a database query listener in Laravel
Source: https://laravel.com/docs/12.x/database
This example illustrates how to register a closure that is invoked for every SQL query executed by your Laravel application using DB::listen(). This functionality is typically registered in a service provider’s boot method and is useful for logging, debugging, or analyzing query patterns.
<?php
namespace App\Providers;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
// ...
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
DB::listen(function (QueryExecuted $query) {
// $query->sql;
// $query->bindings;
// $query->time;
// $query->toRawSql();
});
}
}
Get Item from Laravel Collection by Key with Defaults
Source: https://laravel.com/docs/12.x/collections
The get method retrieves an item from the collection using its key. If the key does not exist, it returns null by default. An optional second argument can provide a default value, which can also be a callback function to compute the default, offering flexible handling of missing keys.
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
$value = $collection->get('name');
// Taylor
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
$value = $collection->get('age', 34);
// 34
$collection->get('email', function () {
return 'taylor@example.com';
});
// taylor@example.com
Retrieve a customer’s upcoming invoice in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
Fetches the next pending invoice for a customer, typically representing the next billing period. This is achieved using the upcomingInvoice method on a billable model.
$invoice = $user->upcomingInvoice();
Create Carbon Instance for Current Time in Laravel
Source: https://laravel.com/docs/12.x/helpers
The now function creates and returns a new Illuminate\Support\Carbon instance, representing the current date and time. This is a convenient way to get a timestamp for the present moment.
$now = now();
Apply Advanced Refresh Configuration with Vite Plugin
Source: https://laravel.com/docs/12.x/vite
Utilize advanced configuration options for the refresh feature by providing a config definition. This allows fine-tuning the refresh behavior, such as setting a delay, using the underlying vite-plugin-full-reload package.
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
// ...
refresh: [
{
paths: ['path/to/watch/**'],
config: { delay: 300 },
},
],
}),
],
});
Generate Laravel Broadcast Channel Class using Artisan
Source: https://laravel.com/docs/12.x/broadcasting
This shell command generates a new broadcast channel class, which helps in organizing authorization logic for channels. The generated class will be placed in the App/Broadcasting directory, promoting cleaner code in your routes/channels.php file.
php artisan make:channel OrderChannel
Display Data Using Blade’s @foreach Directive and Echo Syntax
Source: https://laravel.com/docs/12.x/frontend
This example illustrates how to iterate over a collection of users and display their names using Laravel’s Blade templating engine. It leverages Blade’s @foreach directive and {{ }} syntax for convenient and concise data rendering, which is the recommended modern approach within Laravel for displaying dynamic content.
<div>
@foreach ($users as $user)
Hello, {{ $user->name }} <br />
@endforeach
</div>
Get First Blade Component Attribute Matching a Prefix
Source: https://laravel.com/docs/12.x/blade
This snippet combines whereStartsWith with first to retrieve only the first attribute that matches a specified prefix. It’s useful when you expect only one attribute with a certain prefix or need to prioritize one.
{{ $attributes->whereStartsWith('wire:model')->first() }}
Assert encrypted cookie is missing in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the given encrypted cookie is not present. This ensures a specific encrypted cookie does not exist.
$browser->assertCookieMissing($name);
Inspecting the Request Path with Wildcard in Laravel
Source: https://laravel.com/docs/12.x/requests
This PHP example demonstrates using the is() method on the Request instance to verify if the incoming request path matches a given pattern. It supports using the * character as a wildcard for flexible path matching.
if ($request->is('admin/*')) {
// ...
}
Add Shortcuts to Laravel Command Options
Source: https://laravel.com/docs/12.x/artisan
Explains how to assign a shortcut character to a console command option in Laravel using the | delimiter. It includes an example of how to use the shortcut when executing the command via the terminal, prefixed with a single hyphen.
'mail:send {user} {--Q|queue}'
php artisan mail:send 1 -Qdefault
Create Personal Access Client (Artisan, Shell)
Source: https://laravel.com/docs/12.x/passport
Executes the Artisan command to create a personal access client, which is necessary for users to issue personal access tokens from your application’s UI. This client facilitates a simplified approach to generating API access tokens without a full authorization code flow.
php artisan passport:client --personal
Injecting Dependencies into Laravel MCP Resource Handle Method
Source: https://laravel.com/docs/12.x/mcp
This example illustrates injecting dependencies directly into a resource’s handle method. The service container automatically resolves and provides the type-hinted dependencies when the method is invoked.
<?php
namespace App\Mcp\Resources;
use App\Repositories\WeatherRepository;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Resource;
class WeatherGuidelinesResource extends Resource
{
/**
* Handle the resource request.
*/
public function handle(WeatherRepository $weather): Response
{
$guidelines = $weather->guidelines();
return Response::text($guidelines);
}
}
GET /passport/device/authorizations/authorize
Source: https://laravel.com/docs/12.x/passport
This endpoint is used by the user-code template to process the user code entered by the end-user on a secondary device, initiating the authorization approval flow.
## GET /passport/device/authorizations/authorize
### Description
This endpoint is used by the `auth.oauth.device.user-code` template. After the user navigates to the `verification_uri` and enters the `user_code`, this GET request is made to validate the user code and present the authorization approval screen.
### Method
GET
### Endpoint
/passport/device/authorizations/authorize
### Parameters
#### Path Parameters
_None_
#### Query Parameters
- **user_code** (string) - Required - The user code provided to the end-user for verification.
#### Request Body
_None_
### Request Example
_Not explicitly provided, typically a browser redirect with query parameters._
### Response
#### Success Response (200)
This endpoint typically renders the authorization view for the user to approve or deny. Therefore, it does not return a JSON response directly but rather HTML content.
#### Response Example
_HTML content for authorization view_
Define Interface Implementation with Laravel PHP Bind Attribute
Source: https://laravel.com/docs/12.x/container
This example demonstrates using the #[Bind] attribute directly on an interface to declare its default implementation and environment-specific implementations. This eliminates the need for manual service registration in service providers, allowing Laravel to automatically inject the specified classes based on the active environment.
<?php
namespace App\Contracts;
use App\Services\FakeEventPusher;
use App\Services\RedisEventPusher;
use Illuminate\Container\Attributes\Bind;
#[Bind(RedisEventPusher::class)]
#[Bind(FakeEventPusher::class, environments: ['local', 'testing'])]
interface EventPusher
{
// ...
}
Laravel Route Interacting with Asynchronous Process
Source: https://laravel.com/docs/12.x/processes
This Laravel route demonstrates a common scenario where an asynchronous process is started (Process::start) and its output and error output are continuously logged until the process completes. This highlights the need for sophisticated faking strategies when testing such interactions.
use Illuminate
\Support\Facades\Log;
use Illuminate
\Support\Facades\Route;
Route::get('/import', function () {
$process = Process::start('bash import.sh');
while ($process->running()) {
Log::info($process->latestOutput());
Log::info($process->latestErrorOutput());
}
return 'Done';
});
Creatable API Singleton Resource: Photo Thumbnail
Source: https://laravel.com/docs/12.x/controllers
Defines routes for a creatable single-instance resource intended for API usage, including store, show, update, and destroy operations without create or edit views.
## POST /photos/{photo}/thumbnail
### Description
Store a newly created nested singleton resource in storage via API.
### Method
POST
### Endpoint
/photos/{photo}/thumbnail
### Parameters
#### Path Parameters
- **photo** (integer) - Required - The ID of the parent photo.
#### Query Parameters
None
#### Request Body
- **url** (string) - Required - The URL for the new thumbnail.
### Request Example
{
"url": "/images/api_new_thumbnail_for_photo_123.jpg"
}
### Response
#### Success Response (201)
- **message** (string) - Success message.
- **thumbnail** (object) - The newly created thumbnail resource.
#### Response Example
{
"message": "Thumbnail created successfully via API.",
"thumbnail": {
"id": 3,
"photo_id": 123,
"url": "/images/api_new_thumbnail_for_photo_123.jpg"
}
}
## GET /photos/{photo}/thumbnail
### Description
Display the specified nested singleton resource for API consumption.
### Method
GET
### Endpoint
/photos/{photo}/thumbnail
### Parameters
#### Path Parameters
- **photo** (integer) - Required - The ID of the parent photo.
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **thumbnail** (object) - The thumbnail resource for the given photo.
#### Response Example
{
"id": 1,
"photo_id": 123,
"url": "/images/photo_123_thumbnail.jpg"
}
## PUT/PATCH /photos/{photo}/thumbnail
### Description
Update the specified nested singleton resource in storage via API.
### Method
PUT/PATCH
### Endpoint
/photos/{photo}/thumbnail
### Parameters
#### Path Parameters
- **photo** (integer) - Required - The ID of the parent photo.
#### Query Parameters
None
#### Request Body
- **url** (string) - Required - The new URL for the thumbnail.
### Request Example
{
"url": "/images/api_updated_photo_123_thumbnail.jpg"
}
### Response
#### Success Response (200)
- **message** (string) - Success message.
#### Response Example
{
"message": "Thumbnail updated successfully via API."
}
## DELETE /photos/{photo}/thumbnail
### Description
Remove the specified nested singleton resource from storage via API.
### Method
DELETE
### Endpoint
/photos/{photo}/thumbnail
### Parameters
#### Path Parameters
- **photo** (integer) - Required - The ID of the parent photo.
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (204)
- No Content. Indicates successful deletion.
#### Response Example
(No content)
Get all directories within a directory using Laravel Storage
Source: https://laravel.com/docs/12.x/filesystem
This code illustrates how to fetch a list of all directories directly within a given path using Storage::directories. For a comprehensive list including all subdirectories, Storage::allDirectories is used.
$directories = Storage::directories($directory);
$directories = Storage::allDirectories($directory);
Assert URL scheme equality in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
Verify that the URL’s scheme (e.g., ‘http’ or ‘https’) matches the expected value. This is important for enforcing secure connections or specific protocol requirements.
$browser->assertSchemeIs($scheme);
Assert unencrypted cookie is missing in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the given unencrypted cookie is not present. This ensures a specific plain (unencrypted) cookie does not exist.
$browser->assertPlainCookieMissing($name);
Refresh Browser Page with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This snippet demonstrates how to use the refresh() method to reload the current page in the browser. This can be useful for testing scenarios where page content changes dynamically or needs to be reloaded after an action.
$browser->refresh();
Define Subscription Tax Rates in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP method defines the Stripe tax rate IDs that should apply to a customer’s subscriptions. It must be implemented on your billable model to apply tax rates on a customer-by-customer basis.
/**
* The tax rates that should apply to the customer's subscriptions.
*
* @return array<int, string>
*/
public function taxRates(): array
{
return ['txr_id'];
}
Queue Mail for Background Sending in Laravel
Source: https://laravel.com/docs/12.x/mail
This PHP example shows how to queue an email for background processing using Laravel’s queue() method on the Mail facade. This approach improves application response time by offloading email sending to a queue worker. Requires a properly configured queue system.
Mail::to($request->user())
->cc($moreUsers)
->bcc($evenMoreUsers)
->queue(new OrderShipped($order));
Generate Laravel Service Provider using Artisan CLI
Source: https://laravel.com/docs/12.x/providers
This command utilizes the Laravel Artisan CLI to generate a new service provider class. The framework automatically registers the newly created provider in the bootstrap/providers.php file, simplifying the setup process for custom services or functionalities.
php artisan make:provider RiakServiceProvider
Retrieve invoices including pending ones in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
Fetches a collection of Laravel\Cashier\Invoice instances for a billable model, including any pending invoices that have not yet been finalized. Use the invoicesIncludingPending method for this purpose.
$invoices = $user->invoicesIncludingPending();
Select Radio Input with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
The radio method selects a radio input option. It can find the element via a CSS selector or by matching name and value attributes.
$browser->radio('size', 'large');
Generating JSON Responses with Laravel Facades vs. Helper Functions (PHP)
Source: https://laravel.com/docs/12.x/facades
This snippet illustrates two ways to generate a JSON response in Laravel: using the Response facade and using the global response() helper function. Helper functions offer a more concise syntax as they do not require explicit class imports.
use Illuminate\Support\Facades\Response;
Route::get('/users', function () {
return Response::json([
// ...
]);
});
Route::get('/users', function () {
return response()->json([
// ...
]);
});
Get String Before Last Occurrence (PHP Laravel Str)
Source: https://laravel.com/docs/12.x/strings
The beforeLast method returns the part of the string that precedes the last occurrence of a given value. If the value does not exist in the string, the entire string will be returned. This is useful for getting everything up to the last delimiter.
use Illuminate\Support\Str;
$slice = Str::of('This is my name')->beforeLast('is');
// 'This '
Serialize Eloquent Model Collection to Array (PHP)
Source: https://laravel.com/docs/12.x/eloquent-serialization
This PHP example illustrates how to convert an entire collection of Eloquent models into an array by calling the toArray method on the collection instance.
$users = User::all();
return $users->toArray();
Store Browser Console Output in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This PHP snippet shows how to save the browser’s console output to a file during a Laravel Dusk test. The storeConsoleLog method takes a filename and writes the current console messages to the tests/Browser/console directory, which is useful for debugging client-side errors.
$browser->storeConsoleLog('filename');
Define Laravel Translation String with Placeholder
Source: https://laravel.com/docs/12.x/localization
This PHP example shows how to include placeholders in translation strings. Placeholders are prefixed with a colon (e.g., ‘:name’) and allow for dynamic content insertion when retrieving the translation.
'welcome' => 'Welcome, :name',
Register Custom Cashier Models in Service Provider
Source: https://laravel.com/docs/12.x/cashier-paddle
Inform Cashier about your custom subscription and transaction models by calling Cashier::useSubscriptionModel() and Cashier::useTransactionModel() in your AppServiceProvider’s boot method to ensure Cashier utilizes your extended models.
use App\Models\Cashier\Subscription;
use App\Models\Cashier\Transaction;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Cashier::useSubscriptionModel(Subscription::class);
Cashier::useTransactionModel(Transaction::class);
}
Create Temporary Database Table in Laravel
Source: https://laravel.com/docs/12.x/migrations
This example demonstrates how to create a temporary table that is only visible to the current database session. The temporary() method ensures the table is automatically dropped when the connection is closed, useful for transient data storage.
Schema::create('calculations', function (Blueprint $table) {
$table->temporary();
// ...
});
Assert current URL port in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the current URL port matches the given port. This method is used within browser tests to verify the port of the navigated URL.
$browser->assertPortIs($port);
Define a Laravel queueable job class structure in PHP
Source: https://laravel.com/docs/12.x/queues
This example demonstrates the basic structure of a queueable job class. It includes a constructor for injecting an Eloquent model and a handle method for job execution, leveraging the Queueable trait for model serialization/deserialization and dependency injection for services like AudioProcessor.
<?php
namespace App\Jobs;
use App\Models\Podcast;
use App\Services\AudioProcessor;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class ProcessPodcast implements ShouldQueue
{
use Queueable;
/**
* Create a new job instance.
*/
public function __construct(
public Podcast $podcast,
) {}
/**
* Execute the job.
*/
public function handle(AudioProcessor $processor): void
{
// Process uploaded podcast...
}
}
Handle a Single OS Signal in Laravel Artisan Command
Source: https://laravel.com/docs/12.x/artisan
Illustrates how to register a callback to execute when a specific operating system signal, such as SIGTERM, is received by the Artisan command. This allows for graceful shutdown or custom logic in response to system events.
/**
* Execute the console command.
*/
public function handle(): void
{
$this->trap(SIGTERM, fn () => $this->shouldKeepRunning = false);
while ($this->shouldKeepRunning) {
// ...
}
}
Enable queueing for Laravel Scout operations
Source: https://laravel.com/docs/12.x/scout
Set the queue option to true in your config/scout.php file to enable asynchronous indexing. This offloads search index synchronization to your queue worker, improving web interface response times.
'queue' => true,
Retrieve Laravel Translation with String as Key
Source: https://laravel.com/docs/12.x/localization
When translation strings are used as keys, this PHP example shows how to retrieve the translated value using the ‘__’ helper function, passing the default string directly as the argument.
echo __('I love programming.');
Exclude Blade Component Attributes Starting with a Prefix
Source: https://laravel.com/docs/12.x/blade
The whereDoesntStartWith method is used to exclude attributes whose keys begin with a given string. This allows for filtering out groups of attributes that follow a specific naming pattern.
{{ $attributes->whereDoesntStartWith('wire:model') }}
Create Multiple Distinct Subscriptions in Laravel Cashier (PHP)
Source: https://laravel.com/docs/12.x/billing
This code shows how to allow customers to have multiple distinct subscriptions simultaneously. It uses the newSubscription method with a unique string identifier (e.g., ‘swimming’) to create a separate subscription for the user.
use Illuminate\Http\Request;
Route::post('/swimming/subscribe', function (Request $request) {
$request->user()->newSubscription('swimming')
->price('price_swimming_monthly')
->create($request->paymentMethodId);
// ...
});
Fail Laravel Command Immediately
Source: https://laravel.com/docs/12.x/artisan
This PHP example demonstrates using the fail method within a Laravel Artisan command to immediately terminate its execution and return a non-zero exit code (typically 1). This is a convenient way to signal an unrecoverable error without needing to explicitly return.
$this->fail('Something went wrong.');
Assert any text is present within selector in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that any text is present within the specified CSS selector. This verifies that an element identified by the selector is not empty.
$browser->assertSeeAnythingIn($selector);
Return Eloquent Models from Laravel Route for JSON (PHP)
Source: https://laravel.com/docs/12.x/eloquent-serialization
This Laravel route example demonstrates how the framework automatically serializes Eloquent models and collections to JSON when they are returned directly from routes or controllers.
Route::get('/users', function () {
return User::all();
});
Debit Customer’s Balance
Source: https://laravel.com/docs/12.x/billing
Subtracts a specified amount from a customer’s balance, effectively debiting their account. An optional description can be provided to detail the reason for the debit, which can be useful for tracking penalties or adjustments.
$user->debitBalance(300, 'Bad usage penalty.');
Assert encrypted cookie has value in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that an encrypted cookie has a given value. This verifies both the existence and the content of an encrypted cookie.
$browser->assertCookieValue($name, $value);
Extract Characters from Beginning of Laravel String with Str::take()
Source: https://laravel.com/docs/12.x/strings
The Str::take method returns a specified number of characters from the beginning of a given string. This is useful for extracting prefixes or truncating strings to a certain length from the start.
use Illuminate\Support\Str;
$taken = Str::take('Build something amazing!', 5);
// Build
Define Dynamic Eloquent Relationship at Runtime (PHP)
Source: https://laravel.com/docs/12.x/eloquent-relationships
Explains how to define a relationship dynamically at runtime using the resolveRelationUsing method. This example defines a belongsTo relationship for ‘customer’ on the ‘Order’ model, which can be particularly useful when developing Laravel packages.
use App\Models\Order;
use App\Models\Customer;
Order::resolveRelationUsing('customer', function (Order $orderModel) {
return $orderModel->belongsTo(Customer::class, 'customer_id');
});
Add description to Laravel MCP prompt
Source: https://laravel.com/docs/12.x/mcp
This PHP example illustrates how to provide a meaningful description for a Laravel MCP prompt. By setting the protected $description property within the DescribeWeatherPrompt class, developers can offer crucial context that helps AI models understand the prompt’s purpose and how to best utilize it for generating relevant responses.
class DescribeWeatherPrompt extends Prompt
{
/**
* The prompt's description.
*/
protected string $description = 'Generates a natural-language explanation of the weather for a given location.';
//
}
Inject Dependencies into Prompt Constructor in Laravel MCP
Source: https://laravel.com/docs/12.x/mcp
This PHP example demonstrates constructor-based dependency injection for Laravel MCP prompts. It type-hints a WeatherRepository in the prompt’s constructor, allowing the Laravel service container to automatically resolve and inject the dependency into the prompt instance.
<?php
namespace App\Mcp\Prompts;
use App\Repositories\WeatherRepository;
use Laravel\Mcp\Server\Prompt;
class DescribeWeatherPrompt extends Prompt
{
/**
* Create a new prompt instance.
*/
public function __construct(
protected WeatherRepository $weather,
) {}
//
}
Laravel Controller for Inertia Page Rendering
Source: https://laravel.com/docs/12.x/frontend
This PHP controller example demonstrates returning an Inertia page from a Laravel route instead of a Blade view. It uses the Inertia::render method to pass data, such as a found User model, directly to the specified frontend component. This approach allows seamless data hydration for React or Vue components from the Laravel backend.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Inertia\Inertia;
use Inertia\Response;
class UserController extends Controller
{
/**
* Show the profile for a given user.
*/
public function show(string $id): Response
{
return Inertia::render('users/show', [
'user' => User::findOrFail($id)
]);
}
}
Assert unencrypted cookie is present in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the given unencrypted cookie is present. This method verifies the existence of a plain (unencrypted) cookie by its name.
$browser->assertHasPlainCookie($name);
Assert URL path ends with in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the current URL path ends with the given path. This assertion checks the concluding part of the URL’s path.
$browser->assertPathEndsWith('/home');
Assert encrypted cookie is present in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the given encrypted cookie is present. This method verifies the existence of an encrypted cookie by its name.
$browser->assertHasCookie($name);
Singleton Resource: Profile
Source: https://laravel.com/docs/12.x/controllers
Defines routes for a single-instance resource, typically a user profile or settings, allowing show, edit, and update operations without an identifier.
## GET /profile
### Description
Display the specified singleton resource.
### Method
GET
### Endpoint
/profile
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **profile** (object) - The profile resource.
#### Response Example
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
}
## GET /profile/edit
### Description
Show the form for editing the specified singleton resource.
### Method
GET
### Endpoint
/profile/edit
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- (HTML content) - Form for editing the profile.
#### Response Example
(HTML content of the edit form)
## PUT/PATCH /profile
### Description
Update the specified singleton resource in storage.
### Method
PUT/PATCH
### Endpoint
/profile
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **name** (string) - Required - The new name for the profile.
- **email** (string) - Required - The new email for the profile.
### Request Example
{
"name": "Jane Doe",
"email": "jane.doe@example.com"
}
### Response
#### Success Response (200)
- **message** (string) - Success message.
#### Response Example
{
"message": "Profile updated successfully."
}
Assert unencrypted cookie has value in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that an unencrypted cookie has a given value. This verifies both the existence and the content of a plain (unencrypted) cookie.
$browser->assertPlainCookieValue($name, $value);
Use Precognition useForm with React and Inertia
Source: https://laravel.com/docs/12.x/precognition
This JavaScript example illustrates the usage of useForm from laravel-precognition-react-inertia for creating a form. It demonstrates how to submit the form with Inertia’s visit options, including preserveScroll and onSuccess callbacks for actions like form resetting.
import { useForm } from 'laravel-precognition-react-inertia';
const form = useForm('post', '/users', {
name: '',
email: '',
});
const submit = (e) => {
e.preventDefault();
form.submit({
preserveScroll: true,
onSuccess: () => form.reset(),
});
};
Get Last Element with Laravel Collection last() Method
Source: https://laravel.com/docs/12.x/collections
The last method retrieves the last element from a collection. It can accept an optional callback to define a truth test, or it can be called without arguments to get the absolute last element. If the collection is empty, null is returned.
collect([1, 2, 3, 4])->last(function (int $value, int $key) {
return $value < 3;
});
// 2
collect([1, 2, 3, 4])->last();
// 4
Laravel: Return Redirect with Named Error Bag
Source: https://laravel.com/docs/12.x/validation
When handling multiple forms on a single page, this PHP example demonstrates how to return a redirect response while attaching validation errors to a specific named MessageBag. The Blade example shows how to access these named errors for display in the view.
return redirect('/register')->withErrors($validator, 'login');
{{ $errors->login->first('email') }}
Set up Redis Pub/Sub Listener with PHP
Source: https://laravel.com/docs/12.x/redis
Laravel provides a convenient interface for Redis Pub/Sub. The subscribe method allows an application to listen for messages on a specific channel. This example demonstrates setting up a long-running subscriber within an Artisan command to process incoming messages.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
class RedisSubscribe extends Command
{
/**
*
* @var string
*/
protected $signature = 'redis:subscribe';
/**
*
* @var string
*/
protected $description = 'Subscribe to a Redis channel';
/**
* Execute the console command.
*/
public function handle(): void
{
Redis::subscribe(['test-channel'], function (string $message) {
echo $message;
});
}
}
Add New Laravel Cashier Subscription to Existing Customer
Source: https://laravel.com/docs/12.x/billing
This PHP code demonstrates how to add a new subscription for a customer who already has a default payment method set up in Laravel Cashier. It uses the newSubscription builder followed by the add() method to create the subscription.
use App\Models\User;
$user = User::find(1);
$user->newSubscription('default', 'price_monthly')->add();
Bind Interface to Implementation in Laravel PHP
Source: https://laravel.com/docs/12.x/container
This example illustrates how to register a concrete implementation for a given interface with the Laravel service container using the bind method. When a class type-hints the EventPusher interface, the container will automatically inject an instance of RedisEventPusher.
use App\Contracts\EventPusher;
use App\Services\RedisEventPusher;
$this->app->bind(EventPusher::class, RedisEventPusher::class);
Redirect with Flashed Session Data in Laravel PHP
Source: https://laravel.com/docs/12.x/responses
This example demonstrates redirecting to a new URL while simultaneously flashing data to the session. It’s commonly used after an action to display a success message on the next request. The with() method is chained to the redirect() call.
Route::post('/user/profile', function () {
// ...
return redirect('/dashboard')->with('status', 'Profile updated!');
});
Check if Blade Component Slot is Empty
Source: https://laravel.com/docs/12.x/blade
This example shows how to use the isEmpty() method on a slot variable ($slot) to conditionally render default content if no content has been provided for that slot. Useful for providing fallbacks.
<span class="alert-title">{{ $title }}</span>
<div class="alert alert-danger">
@if ($slot->isEmpty())
This is default content if the slot is empty.
@else
{{ $slot }}
@endif
</div>
Laravel Dusk: Selecting a random option from a dropdown
Source: https://laravel.com/docs/12.x/dusk
This snippet shows how to select a random option from a <select> element. By omitting the second argument to the select method, Dusk will automatically choose an available option.
$browser->select('size');
Assert URL host inequality in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
Use this assertion to check that the current URL’s host does not match a specified value. It helps in validating redirects or ensuring access to specific domains.
$browser->assertHostIsNot($host);
Wait for Asynchronous Process Completion in Laravel
Source: https://laravel.com/docs/12.x/processes
After starting an asynchronous process, the wait() method can be called on the PendingProcess instance to pause execution until the process has finished, subsequently retrieving its ProcessResult.
$process = Process::timeout(120)->start('bash import.sh');
// ...
$result = $process->wait();
Check for Incomplete Subscription Payments (PHP)
Source: https://laravel.com/docs/12.x/billing
Demonstrates how to check if a user or a specific subscription has an incomplete payment requiring further action using the hasIncompletePayment method. This method helps identify subscriptions that are not active due to pending payment confirmation.
if ($user->hasIncompletePayment('default')) {
// ...
}
if ($user->subscription('default')->hasIncompletePayment()) {
// ...
}
Create First-Party Laravel Passport Client via Artisan
Source: https://laravel.com/docs/12.x/passport
Provides the Artisan command to create a first-party client for Laravel Passport from the command line. This interactive command prompts for client details and subsequently issues a client ID and secret necessary for authentication.
php artisan passport:client
Schedule Laravel Cashier Subscription Cancellation (PHP)
Source: https://laravel.com/docs/12.x/billing
Schedule a subscription cancellation to occur at a specific future moment in time. This allows for planned service termination while retaining current access until the specified date.
$user->subscription('default')->cancelAt(
now()->addDays(10)
);
Configure Default Currency for Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This .env setting specifies the default currency Cashier will use for billing operations. By default, Cashier uses USD, but this allows you to change it to another currency like EUR.
CASHIER_CURRENCY=eur
Run Specific Laravel Dusk Tests by Group (Shell)
Source: https://laravel.com/docs/12.x/dusk
Pass PHPUnit/Pest arguments, such as --group=foo, to the php artisan dusk command to run a specific subset of your Laravel Dusk tests. This allows for targeted testing of related functionalities or modules.
php artisan dusk --group=foo
Dispatch a Laravel Job Batch with Completion Callbacks (PHP)
Source: https://laravel.com/docs/12.x/queues
This example demonstrates how to dispatch a batch of jobs in Laravel, defining before, progress, then, catch, and finally callbacks to handle various stages of batch execution. It processes rows from a CSV file using ImportCsv jobs and returns the batch ID upon dispatch.
use App\Jobs\ImportCsv;
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Bus;
use Throwable;
$batch = Bus::batch([
new ImportCsv(1, 100),
new ImportCsv(101, 200),
new ImportCsv(201, 300),
new ImportCsv(301, 400),
new ImportCsv(401, 500),
])->before(function (Batch $batch) {
// The batch has been created but no jobs have been added...
})->progress(function (Batch $batch) {
// A single job has completed successfully...
})->then(function (Batch $batch) {
// All jobs completed successfully...
})->catch(function (Batch $batch, Throwable $e) {
// First batch job failure detected...
})->finally(function (Batch $batch) {
// The batch has finished executing...
})->dispatch();
return $batch->id;
Customize Scroll Behavior in Search Results (Laravel PHP)
Source: https://laravel.com/docs/12.x/prompts
Shows how to control the number of options displayed before the search results list starts to scroll. The scroll argument allows customization of this behavior, with a default of five options.
$id = search(
label: 'Search for the user that should receive the mail',
options: fn (string $value) => strlen($value) > 0
? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
: [],
scroll: 10
);
Add Billable Trait to User Model
Source: https://laravel.com/docs/12.x/cashier-paddle
Apply the Billable trait from Laravel\Paddle to your User model to enable billing functionalities like subscription management and payment method updates for users.
use Laravel\Paddle\Billable;
class User extends Authenticatable
{
use Billable;
}
Inject Dependencies into Laravel Service Provider Boot Method (PHP)
Source: https://laravel.com/docs/12.x/providers
This example shows how to use dependency injection within the boot method of a Laravel service provider. By type-hinting dependencies, the Laravel service container automatically injects the required services, like ResponseFactory, allowing for custom macro definitions.
use IlluminateContractsRoutingResponseFactory;
/**
* Bootstrap any application services.
*/
public function boot(ResponseFactory $response): void
{
$response->macro('serialized', function (mixed $value) {
// ...
});
}
Customized Anonymous Broadcast Event Structure (JSON)
Source: https://laravel.com/docs/12.x/broadcasting
After customizing the event name and data, the broadcasted JSON payload will reflect these changes. The ‘event’ property will match the name provided, and ‘data’ will contain the serialized object.
{
"event": "OrderPlaced",
"data": "{ id: 1, total: 100 }",
"channel": "orders.1"
}
Swap Prices on Existing Subscription in Laravel
Source: https://laravel.com/docs/12.x/cashier-paddle
Shows how to add or swap prices on an existing subscription using the swap method. It’s crucial to include existing prices and quantities to avoid unintended removals. The customer is billed at the next billing cycle.
$user = User::find(1);
$user->subscription()->swap(['price_chat', 'price_original' => 2]);
Assert no text is present within selector in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that no text is present within the specified CSS selector. This verifies that an element identified by the selector is empty.
$browser->assertSeeNothingIn($selector);
Cancel Laravel Cashier Subscription Immediately (PHP)
Source: https://laravel.com/docs/12.x/billing
Perform an immediate cancellation of a user’s subscription, bypassing any grace period. This will set the ends_at column to the current timestamp.
$user->subscription('default')->cancelNow();
Assert URL hash fragment is exact in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the URL’s current hash fragment matches the given fragment. This verifies the exact value of the URL’s anchor.
$browser->assertFragmentIs('anchor');
Get the front controller path for a Valet application (PHP)
Source: https://laravel.com/docs/12.x/valet
The frontControllerPath method returns the absolute path to the application’s front controller, which is usually an index.php file. This is the entry point for processing dynamic requests within the application.
/**
* Get the fully resolved path to the application's front controller.
*/
public function frontControllerPath(string $sitePath, string $siteName, string $uri): string
{
return $sitePath.'/public/index.php';
}
Implement broadcastOn for Multiple Channels in Laravel Event
Source: https://laravel.com/docs/12.x/broadcasting
This PHP snippet demonstrates how to configure the broadcastOn method to return an array of channels. This allows an event to be simultaneously broadcast across multiple private channels, providing flexibility for diverse notification requirements.
use IlluminateBroadcastingPrivateChannel;
/**
* Get the channels the event should broadcast on.
*
* @return array<int, \Illuminate\Broadcasting\Channel>
*/
public function broadcastOn(): array
{
return [
new PrivateChannel('orders.'.$this->order->id),
// ...
];
}
Define and Use Shorthand Selectors in Laravel Dusk Page Objects
Source: https://laravel.com/docs/12.x/dusk
Illustrates how to define and utilize shorthand selectors within Dusk Page objects. The elements method maps custom aliases to CSS selectors, while siteElements can define global shortcuts, simplifying interaction with complex elements in tests.
/**
* Get the element shortcuts for the page.
*
* @return array<string, string>
*/
public function elements(): array
{
return [
'@email' => 'input[name=email]',
];
}
$browser->type('@email', 'taylor@laravel.com');
/**
* Get the global element shortcuts for the site.
*
* @return array<string, string>
*/
public static function siteElements(): array
{
return [
'@element' => '#selector',
];
}
Publish Laravel Pulse Configuration and Migrations
Source: https://laravel.com/docs/12.x/pulse
Publishes the essential configuration file and database migration files for Laravel Pulse to your application’s directories. This step makes Pulse’s settings and database schemas accessible for review and modification.
php artisan vendor:publish --provider="Laravel\Pulse\PulseServiceProvider"
Stop Further Chunk Processing in Laravel
Source: https://laravel.com/docs/12.x/queries
This PHP example demonstrates how to stop the chunk method from processing further chunks by returning false from the provided closure. This is useful for conditional termination of batch processing.
DB::table('users')->orderBy('id')->chunk(100, function (Collection $users) {
// Process the records...
return false;
});
Call multiple Laravel seeder classes from a parent seeder
Source: https://laravel.com/docs/12.x/seeding
This example demonstrates how to execute several seeder classes from within a main seeder using the call method. This approach allows for breaking down complex seeding logic into smaller, manageable files, improving organization and reusability.
/**
* Run the database seeders.
*/
public function run(): void
{
$this->call([
UserSeeder::class,
PostSeeder::class,
CommentSeeder::class,
]);
}
Swap Price on a Named Subscription in Laravel Cashier (PHP)
Source: https://laravel.com/docs/12.x/billing
After creating a named subscription (e.g., ‘swimming’), this snippet demonstrates how to adjust its price. It targets the specific subscription by its name and then calls the swap method to change the associated price.
$user->subscription('swimming')->swap('price_swimming_yearly');
Define Laravel Envoy Servers and Tasks
Source: https://laravel.com/docs/12.x/envoy
This example defines an array of remote servers (‘web’, ‘workers’) and a task named ‘restart-queues’ to be executed specifically on the ‘workers’ server. The task navigates to a directory and runs a PHP Artisan command.
@servers(['web' => ['user@192.168.1.1'], 'workers' => ['user@192.168.1.2']])
@task('restart-queues', ['on' => 'workers'])
cd /home/user/example.com
php artisan queue:restart
@endtask
Specify Tables for Database Truncation (PHP)
Source: https://laravel.com/docs/12.x/dusk
Define the $tablesToTruncate property in your test class to explicitly list which database tables should be truncated by the DatabaseTruncation trait. This allows fine-grained control over the truncation process, targeting only necessary tables.
/**
* Indicates which tables should be truncated.
*
* @var array
*/
protected $tablesToTruncate = ['users'];
Get Client IP Addresses from Laravel Request
Source: https://laravel.com/docs/12.x/requests
The Request object provides methods to retrieve the client’s IP address. Use ip() for the primary client IP, or ips() to get an array of all forwarded IP addresses, with the original client’s IP at the end. Note that IP addresses are user-controlled and should be treated as untrusted input for security purposes.
$ipAddress = $request->ip();
$ipAddresses = $request->ips();
Laravel Dusk: Typing text into an input field
Source: https://laravel.com/docs/12.x/dusk
This snippet shows how to use the type method to simulate typing text into an input field. Dusk can locate the input field by its name attribute if a CSS selector is not provided, making interaction straightforward.
$browser->type('email', 'taylor@laravel.com');
Define and Use Custom Methods in Laravel Dusk Page Objects
Source: https://laravel.com/docs/12.x/dusk
Shows how to create and invoke custom methods within a Dusk Page object to encapsulate complex test interactions. These methods receive the browser instance as the first argument, allowing for cleaner, more reusable test logic.
<?php
nemespace Tests\Browser\Pages;
use Laravel\Dusk\Browser;
use Laravel\Dusk\Page;
class Dashboard extends Page
{
// Other page methods...
/**
* Create a new playlist.
*/
public function createPlaylist(Browser $browser, string $name): void
{
$browser->type('name', $name)
->check('share')
->press('Create Playlist');
}
}
use Tests\Browser\Pages\Dashboard;
$browser->visit(new Dashboard)
->createPlaylist('My Playlist')
->assertSee('My Playlist');
Switch Vue Application Layout
Source: https://laravel.com/docs/12.x/starter-kits
This JavaScript snippet illustrates how to change the primary application layout in a Vue starter kit. By modifying the import statement in resources/js/layouts/AppLayout.vue, users can switch between a default sidebar layout and an alternative header layout.
import AppLayout from '@/layouts/app/AppSidebarLayout.vue'; // [tl! remove]
import AppLayout from '@/layouts/app/AppHeaderLayout.vue'; // [tl! add]
Attach a View Composer to All Views using Wildcard (Laravel PHP)
Source: https://laravel.com/docs/12.x/views
This PHP example shows how to register a view composer that applies to all views in the application. Using the wildcard character * with the View::composer method ensures that the provided closure or class is executed for every view. This is useful for injecting global data or performing actions on all rendered views.
use Illuminate\Support\Facades;
use Illuminate\View\View;
Facades\View::composer('*', function (View $view) {
// ...
});
Assert URL scheme inequality in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This assertion ensures that the current URL’s scheme does not match a specified value. Useful for confirming a page is not using an undesired protocol.
$browser->assertSchemeIsNot($scheme);
Invoice a Single Item with Price ID (PHP)
Source: https://laravel.com/docs/12.x/billing
Demonstrates how to create an invoice for a specific quantity of an item using its predefined Stripe Price ID. The invoicePrice method immediately charges the customer’s default payment method and is ideal for offering PDF invoices.
$user->invoicePrice('price_tshirt', 5);
Fake All Processes and Assert Runs in Laravel Tests
Source: https://laravel.com/docs/12.x/processes
This snippet demonstrates how to fake all process calls using Process::fake() and then assert that a specific command was run. It includes examples for both Pest and PHPUnit testing frameworks, showing simple string assertions and more detailed assertions using callbacks to inspect process configuration like command and timeout.
<?php
use Illuminate\Contracts\Process\ProcessResult;
use Illuminate\Process\PendingProcess;
use Illuminate\Support\Facades\Process;
test('process is invoked', function () {
Process::fake();
$response = $this->get('/import');
// Simple process assertion...
Process::assertRan('bash import.sh');
// Or, inspecting the process configuration...
Process::assertRan(function (PendingProcess $process, ProcessResult $result) {
return $process->command === 'bash import.sh' &&
$process->timeout === 60;
});
});
<?php
namespace Tests\Feature;
use Illuminate\Contracts\Process\ProcessResult;
use Illuminate\Process\PendingProcess;
use Illuminate\Support\Facades\Process;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_process_is_invoked(): void
{
Process::fake();
$response = $this->get('/import');
// Simple process assertion...
Process::assertRan('bash import.sh');
// Or, inspecting the process configuration...
Process::assertRan(function (PendingProcess $process, ProcessResult $result) {
return $process->command === 'bash import.sh' &&
$process->timeout === 60;
});
}
}
Assert URL path contains in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the current URL path contains the given path. This method checks for the presence of a substring within the URL’s path.
$browser->assertPathContains('/home');
Inject variadic tagged dependencies in Laravel
Source: https://laravel.com/docs/12.x/container
This example shows how to inject all container bindings associated with a specific tag into a variadic dependency. Using giveTagged('reports') ensures that all services previously tagged as ‘reports’ are provided to the ReportAggregator class.
$this->app->when(ReportAggregator::class)
->needs(Report::class)
->giveTagged('reports');
Laravel Collection: count() method
Source: https://laravel.com/docs/12.x/collections
The count method provides a straightforward way to get the total number of items currently present within the collection.
$collection = collect([1, 2, 3, 4]);
$collection->count();
// 4
Retrieve a specific invoice by ID in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
Retrieves a single Laravel\Cashier\Invoice instance by its unique ID for a billable model using the findInvoice method. This is useful for accessing details of a particular invoice.
$invoice = $user->findInvoice($invoiceId);
Store File on Default Disk using Laravel Storage Facade
Source: https://laravel.com/docs/12.x/filesystem
This example demonstrates storing file content on the application’s default filesystem disk using the Storage facade’s ‘put’ method. If no specific disk is chosen, the operation is automatically directed to the default disk configured in ‘filesystems.php’.
use Illuminate\Support\Facades\Storage;
Storage::put('avatars/1', $content);
Listen to fully qualified event class in Laravel Echo (JavaScript)
Source: https://laravel.com/docs/12.x/broadcasting
This snippet shows how to listen to an event using its fully qualified class name in Laravel Echo. By prefixing the event name with a dot (.), you can bypass the configured root namespace and directly specify the complete class path.
Echo.channel('orders').listen('.Namespace\\Event\\Class', (e) => {
// ...
});
Press Button and Wait for Re-enable with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
The pressAndWaitFor method clicks a button and then waits for it to be re-enabled. This is useful for forms that disable submission buttons. An optional maximum wait time in seconds can be specified.
// Press the button and wait a maximum of 5 seconds for it to be enabled...
$browser->pressAndWaitFor('Save');
// Press the button and wait a maximum of 1 second for it to be enabled...
$browser->pressAndWaitFor('Save', 1);
Create Payment Intent using Laravel Cashier’s pay method
Source: https://laravel.com/docs/12.x/billing
Demonstrates how to create a Stripe payment intent for a user using the pay method on a billable model, returning the client secret for frontend processing. The amount provided should be in the lowest currency denominator (e.g., cents for USD).
use Illuminate\Http\Request;
Route::post('/pay', function (Request $request) {
$payment = $request->user()->pay(
$request->get('amount')
);
return $payment->client_secret;
});
Implement Constructor Injection in Laravel Controllers with PHP
Source: https://laravel.com/docs/12.x/controllers
This example shows how Laravel’s service container resolves and injects dependencies type-hinted in a controller’s constructor. By type-hinting an interface or class, such as UserRepository, Laravel automatically provides an instance of that dependency when the controller is instantiated, promoting testability and modularity.
<?php
namespace App\Http\Controllers;
use App\Repositories\UserRepository;
class UserController extends Controller
{
/**
* Create a new controller instance.
*/
public function __construct(
protected UserRepository $users,
) {}
}
Authorize Private Channels in Laravel routes/channels.php
Source: https://laravel.com/docs/12.x/broadcasting
This PHP code illustrates how to define authorization rules for private channels within Laravel’s routes/channels.php file. It verifies that a user attempting to listen to the orders.{orderId} channel is the actual creator of the specified order, enhancing security and access control.
use AppModelsOrder;
use AppModelsUser;
Broadcast::channel('orders.{orderId}', function (User $user, int $orderId) {
return $user->id === Order::findOrNew($orderId)->user_id;
});
Resolve Inertia Page Components with Laravel Vite Plugin
Source: https://laravel.com/docs/12.x/vite
This JavaScript snippet demonstrates using the resolvePageComponent function from laravel-vite-plugin/inertia-helpers within an Inertia.js application. It configures Inertia to dynamically load Vue 3 page components from a specified directory, enhancing component resolution.
import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/vue3';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
createInertiaApp({
resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.mount(el);
},
});
Swap Subscription Plan in Laravel Cashier (PHP)
Source: https://laravel.com/docs/12.x/cashier-paddle
This Laravel PHP route handler enables users to swap their current subscription plan to a new one using Cashier’s swap method. It accepts a price identifier and redirects the user to the dashboard upon successful update. This functionality requires an authenticated user and a properly configured Cashier integration with Paddle.
use Illuminate\Http\Request;
Route::put('/subscription/{price}/swap', function (Request $request, $price) {
$user->subscription()->swap($price); // With "$price" being "price_basic_yearly" for this example.
return redirect()->route('dashboard');
})->name('subscription.swap');
Default Anonymous Broadcast Event Structure (JSON)
Source: https://laravel.com/docs/12.x/broadcasting
When a basic anonymous event is broadcast, it will typically have this structure. The ‘event’ property defaults to ‘AnonymousEvent’, ‘data’ is an empty array, and ‘channel’ reflects the specified channel.
{
"event": "AnonymousEvent",
"data": "[]",
"channel": "orders.1"
}
Dynamically update progress bar label and hint in Laravel Prompts
Source: https://laravel.com/docs/12.x/prompts
This example demonstrates how to pass the Laravel\Prompts\Progress instance to your callback, enabling dynamic modification of the progress bar’s label and hint during each iteration. This provides more detailed real-time feedback to the user on the current item being processed.
$users = progress(
label: 'Updating users',
steps: User::all(),
callback: function ($user, $progress) {
$progress
->label("Updating {$user->name}")
->hint("Created on {$user->created_at}");
return $this->performTask($user);
},
hint: 'This may take some time.'
);
Subscribe to Redis Wildcard Channels with PHP
Source: https://laravel.com/docs/12.x/redis
The psubscribe method allows subscribing to wildcard channels, such as * for all channels or users.* for channels starting with ‘users.’. The provided closure receives both the message and the specific channel name for processing.
Redis::psubscribe(['*'], function (string $message, string $channel) {
echo $message;
});
Redis::psubscribe(['users.*'], function (string $message, string $channel) {
echo $message;
});
Define Named and Default Slots in Blade Component
Source: https://laravel.com/docs/12.x/blade
This example modifies the alert component to include a named slot, $title, alongside the default $slot. It shows how to structure a component view to accommodate multiple content areas.
<!-- /resources/views/components/alert.blade.php -->
<span class="alert-title">{{ $title }}</span>
<div class="alert alert-danger">
{{ $slot }}
</div>
Swap Subscription Plan in Laravel Cashier Paddle
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP code demonstrates how to change a user’s current subscription plan to a new one by passing the Paddle price identifier to the swap method. It assumes a User model with an active subscription.
use App\Models\User;
$user = User::find(1);
$user->subscription()->swap($premium = 'pri_456');
Manually Configure Laravel’s Default Global Middleware Stack
Source: https://laravel.com/docs/12.x/middleware
This example shows how to take manual control over Laravel’s default global middleware by providing a custom array. By using the use method, developers can customize, add, or remove default middleware components, such as TrustProxies or HandleCors, to suit specific application needs in bootstrap/app.php.
->withMiddleware(function (Middleware $middleware): void {
$middleware->use([
\Illuminate\Foundation\Http\Middleware\InvokeDeferredCallbacks::class,
// \Illuminate\Http\Middleware\TrustHosts::class,
\Illuminate\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Http\Middleware\ValidatePostSize::class,
\Illuminate\Foundation\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
]);
})
Example Code Using Incremental Sleep for Testing
Source: https://laravel.com/docs/12.x/helpers
This code illustrates a common scenario where an application uses the Sleep class with an incrementally increasing delay. This type of code typically slows down tests significantly, highlighting the need for the Sleep faking mechanism.
$waiting = /* ... */;
$seconds = 1;
while ($waiting) {
Sleep::for($seconds++)->seconds();
$waiting = /* ... */;
}
Swap Subscription Plan Without Proration in Laravel Cashier Paddle
Source: https://laravel.com/docs/12.x/cashier-paddle
This PHP code illustrates how to update a user’s subscription plan without applying proration charges. The noProrate method is chained before the swap call.
$user->subscription('default')->noProrate()->swap($premium = 'pri_456');
Assert element count by selector in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that elements matching the given selector appear the specified number of times. This is useful for verifying the quantity of specific DOM elements.
$browser->assertCount($selector, $count);
Dispatching Laravel Jobs to Queues (PHP)
Source: https://laravel.com/docs/12.x/queues
Demonstrates how to dispatch a job in Laravel, showing both dispatching to the default queue configured for a connection and explicitly dispatching a job to a specific named queue, such as ‘emails’.
use App\Jobs\ProcessPodcast;
// This job is sent to the default connection's default queue...
ProcessPodcast::dispatch();
// This job is sent to the default connection's "emails" queue...
ProcessPodcast::dispatch()->onQueue('emails');
Get Underlying Array from Laravel Collection (all)
Source: https://laravel.com/docs/12.x/collections
The all method returns the underlying plain PHP array that the collection represents. This can be useful for converting a collection back to a standard array.
collect([1, 2, 3])->all();
// [1, 2, 3]
Configure Per-Query Thresholds for Slow Queries Recorder (PHP)
Source: https://laravel.com/docs/12.x/pulse
This example demonstrates how to specify different time thresholds for individual database queries within the SlowQueries recorder configuration. Queries matching a regular expression (e.g., for an insert statement) will use their dedicated threshold, while all other queries will fall back to the default threshold defined by an environment variable.
Recorders\SlowQueries::class => [
// ...
'threshold' => [
'#^insert into `yearly_reports`#' => 5000,
'default' => env('PULSE_SLOW_QUERIES_THRESHOLD', 1000),
],
],
Assert User is Guest (Not Authenticated) in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This method asserts that the current user is not authenticated, meaning they are considered a guest. Useful for testing public-facing pages or after a logout functionality.
$browser->assertGuest();
Check for value in Laravel Context Stack with custom logic
Source: https://laravel.com/docs/12.x/context
Illustrates passing a closure to Context::stackContains for more complex value comparison. This allows for custom logic, such as checking if a stack item starts with a specific string.
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;
return Context::stackContains('breadcrumbs', function ($value) {
return Str::startsWith($value, 'query_');
});
Check for Cache Item Existence in Laravel (PHP)
Source: https://laravel.com/docs/12.x/cache
This PHP example demonstrates the use of the Cache::has() method to determine if a specific item exists in the cache. It returns true if the item is present and its value is not null.
if (Cache::has('key')) {
// ...
}
Retrieve Single Column Values with Laravel pluck
Source: https://laravel.com/docs/12.x/queries
This PHP example demonstrates how to use the pluck method on the DB facade to retrieve an Illuminate\Support\Collection of values from a single column. It shows iterating over the retrieved titles.
use Illuminate\Support\Facades\DB;
$titles = DB::table('users')->pluck('title');
foreach ($titles as $title) {
echo $title;
}
Inject the Laravel service container instance into a class constructor
Source: https://laravel.com/docs/12.x/container
This example demonstrates how to have the Laravel container instance itself injected directly into a class’s constructor when that class is resolved by the container. This is achieved by type-hinting Illuminate\Container\Container in the constructor.
use Illuminate\Container\Container;
/**
* Create a new class instance.
*/
public function __construct(
protected Container $container,
) {}
Laravel Dusk: Typing text slowly into an input field
Source: https://laravel.com/docs/12.x/dusk
The typeSlowly method simulates typing with a delay between key presses, defaulting to 100 milliseconds. You can customize this delay by providing a third argument, which is useful for testing asynchronous interactions or animations.
$browser->typeSlowly('mobile', '+1 (202) 555-5555');
$browser->typeSlowly('mobile', '+1 (202) 555-5555', 300);
Load Package View in Laravel Route (PHP)
Source: https://laravel.com/docs/12.x/packages
After registering your package’s view path in a service provider, you can load specific views using the package::view convention. This example demonstrates loading a dashboard view from the courier package within a Laravel route closure.
Route::get('/dashboard', function () {
return view('courier::dashboard');
});
Assert User Authenticated in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This assertion verifies that a user is currently authenticated within the application. It’s a general check for the user’s login status, ensuring they are logged in.
$browser->assertAuthenticated();
Retrieve File Contents from Laravel Storage Disk
Source: https://laravel.com/docs/12.x/filesystem
The ‘get’ method of the Storage facade is used to retrieve the raw string contents of a file. File paths should always be specified relative to the root directory of the chosen disk.
$contents = Storage::get('file.jpg');
Laravel Prompts Confirm Required ‘Yes’
Source: https://laravel.com/docs/12.x/prompts
Details how to enforce a ‘Yes’ selection for the confirm prompt in Laravel Prompts. It includes examples for requiring a ‘Yes’ with a simple boolean and with a custom validation message for clarity.
$confirmed = confirm(
label: 'Do you accept the terms?',
required: true
);
$confirmed = confirm(
label: 'Do you accept the terms?',
required: 'You must accept the terms to continue.'
);
Pass Arguments to Scheduled Laravel Artisan Closure Commands
Source: https://laravel.com/docs/12.x/scheduling
This PHP example demonstrates how to pass arguments to an Artisan command defined as a closure when scheduling it. The arguments are provided as an array to the schedule method, ensuring they are available to the closure during execution.
Artisan::command('emails:send {user} {--force}', function ($user) {
// ...
})->purpose('Send emails to the specified user')->schedule(['Taylor', '--force'])->daily();
Retrieve Configuration Values in Laravel
Source: https://laravel.com/docs/12.x/helpers
The config function is used to get the value of a configuration variable. Configuration values can be accessed using ‘dot’ syntax, and a default value can be provided if the specified option does not exist.
$value = config('app.timezone');
$value = config('app.timezone', $default);
Assert current URL equality in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This assertion confirms that the browser’s current URL, excluding any query string parameters, matches the provided string. It’s crucial for validating navigation and redirects.
$browser->assertUrlIs($url);
Implement Laravel Envoy @before Hook (Blade/PHP)
Source: https://laravel.com/docs/12.x/envoy
This Blade snippet shows the @before hook, which executes PHP code locally before each task execution. It receives the name of the task about to be executed, allowing for conditional logic or setup based on the upcoming task.
@before
if ($task === 'deploy') {
// ...
}
@endbefore
Display Paddle subtotal and tax amounts in Blade
Source: https://laravel.com/docs/12.x/cashier-paddle
This Blade template demonstrates how to present individual components of a Paddle price. It loops through a collection of prices, showing the product name, its subtotal, and the separate tax amount. This allows for detailed price breakdown display.
<ul>
@foreach ($prices as $price)
<li>{{ $price->product['name'] }} - {{ $price->subtotal() }} (+ {{ $price->tax() }} tax)</li>
@endforeach
</ul>
Invoke Closure When String Is ASCII (PHP)
Source: https://laravel.com/docs/12.x/strings
The whenIsAscii method invokes a closure if the string is 7-bit ASCII. The closure receives the fluent string instance. This example converts the string to title case if it is ASCII.
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('laravel')->whenIsAscii(function (Stringable $string) {
return $string->title();
});
// 'Laravel'
Assert URL hash fragment is not exact in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the URL’s current hash fragment does not match the given fragment. This ensures the URL’s anchor is not a specific value.
$browser->assertFragmentIsNot('anchor');
Perform Single Charge Checkout for Ad-hoc Products with Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This code demonstrates using checkoutCharge to perform a simple charge for an ad-hoc product not predefined in Stripe. It accepts an amount, product name, and optional quantity, creating a new product and price in Stripe, then redirects the customer to the checkout page. Note that this method creates new products in Stripe.
use IlluminateHttpRequest;
Route::get('/charge-checkout', function (Request $request) {
return $request->user()->checkoutCharge(1200, 'T-Shirt', 5);
});
Construct URI Templates for Laravel HTTP Requests
Source: https://laravel.com/docs/12.x/http-client
This example demonstrates how to use URI templates with Laravel’s HTTP client. The withUrlParameters method allows you to define variables that are expanded into the URL string according to the URI template specification (RFC 6570).
Http::withUrlParameters([
'endpoint' => 'https://laravel.com',
'page' => 'docs',
'version' => '12.x',
'topic' => 'validation',
])->get('{+endpoint}/{page}/{version}/{topic}');
Benchmark PHP code with multiple iterations in Laravel
Source: https://laravel.com/docs/12.x/helpers
This example shows how to benchmark a PHP callback multiple times using Benchmark::dd by specifying the number of iterations as the second argument. The method returns the average execution time across all iterations, providing a more reliable performance measurement.
Benchmark::dd(fn () => User::count(), iterations: 10); // 0.5 ms
Initialize Laravel Stream with an Initial Payload in React/Vue
Source: https://laravel.com/docs/12.x/responses
This example shows how to provide an initialInput payload to the useStream hook. This option sends data to the stream upon initialization, allowing the backend to process an initial request without requiring a separate send call.
import { useStream } from '@laravel/stream-react';
function App() {
const { data } = useStream('chat', {
initialInput: {
message: 'Introduce yourself.',
},
});
return <div>{data}</div>;
}
<script setup lang="ts">
import { useStream } from '@laravel/stream-vue';
const { data } = useStream('chat', {
initialInput: {
message: 'Introduce yourself.',
},
});
</script>
<template>
<div>{{ data }}</div>
</template>
Create a Collection Instance with Helper in PHP
Source: https://laravel.com/docs/12.x/collections
This snippet shows the simplest way to create a new Illuminate\Support\Collection instance. The collect helper function takes an array and wraps it, making all collection methods available for fluent operations.
$collection = collect([1, 2, 3]);
Publish Laravel Package Language Files
Source: https://laravel.com/docs/12.x/packages
This PHP snippet shows how to register and then publish a package’s language files to the application’s lang/vendor directory. It first uses loadTranslationsFrom for runtime access and then employs the publishes method to map the package’s language directory to the vendor path, allowing users to customize them via the vendor:publish Artisan command.
/**
* Bootstrap any package services.
*/
public function boot(): void
{
$this->loadTranslationsFrom(__DIR__.'/../lang', 'courier');
$this->publishes([
__DIR__.'/../lang' => $this->app->langPath('vendor/courier'),
]);
}
Get All Traits Used by a Class Recursively in Laravel
Source: https://laravel.com/docs/12.x/helpers
The class_uses_recursive function identifies and returns all traits that a given class uses, including those inherited from all of its parent classes.
$traits = class_uses_recursive(App\Models\User::class);
Redirect to Stripe billing portal with custom return URL using Cashier (PHP)
Source: https://laravel.com/docs/12.x/billing
This snippet extends the billing portal redirection by providing a custom URL as an argument to redirectToBillingPortal. After managing their subscription, the user will be returned to this specified URL, allowing for a seamless return to a specific part of your application.
use Illuminate\Http\Request;
Route::get('/billing-portal', function (Request $request) {
return $request->user()->redirectToBillingPortal(route('billing'));
});
Enable Promotion Codes for Laravel Cashier Checkout
Source: https://laravel.com/docs/12.x/billing
This snippet shows how to enable user-redeemable promotion codes on your Stripe Checkout page. By chaining the allowPromotionCodes() method before calling checkout(), you can allow customers to apply discounts during the checkout process.
use IlluminateHttpRequest;
Route::get('/product-checkout', function (Request $request) {
return $request->user()
->allowPromotionCodes()
->checkout('price_tshirt');
});
Inspect view data directly in Laravel tests (Pest/PHPUnit)
Source: https://laravel.com/docs/12.x/http-tests
Demonstrates how to access and inspect view data directly as array variables on the Laravel TestResponse instance. Examples are provided for both Pest and PHPUnit testing frameworks.
expect($response['name'])->toBe('Taylor');
$this->assertEquals('Taylor', $response['name']);
Laravel: Validate UUID with Specific Version
Source: https://laravel.com/docs/12.x/validation
This code shows how to validate a Universally Unique Identifier (UUID) in Laravel, ensuring it matches a specific version. In this example, it validates that the UUID is of version 4.
'uuid' => 'uuid:4'
Test file uploads with fake storage and files in Laravel
Source: https://laravel.com/docs/12.x/http-tests
These PHP examples (Pest and PHPUnit) illustrate how to test file uploads in a Laravel application. They use Storage::fake() to mock the disk and UploadedFile::fake()->image() to create a dummy image file. The test simulates an upload and then asserts that the fake file exists on the mocked storage, simplifying file upload testing without interacting with the actual filesystem.
<?php
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
test('avatars can be uploaded', function () {
Storage::fake('avatars');
$file = UploadedFile::fake()->image('avatar.jpg');
$response = $this->post('/avatar', [
'avatar' => $file,
]);
Storage::disk('avatars')->assertExists($file->hashName());
});
<?php
namespace Tests\Feature;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_avatars_can_be_uploaded(): void
{
Storage::fake('avatars');
$file = UploadedFile::fake()->image('avatar.jpg');
$response = $this->post('/avatar', [
'avatar' => $file,
]);
Storage::disk('avatars')->assertExists($file->hashName());
}
}
Flush Single Tagged Cache Items in Laravel
Source: https://laravel.com/docs/12.x/cache
This example illustrates how to flush cache items that are specifically associated with a single tag (e.g., ‘authors’). Only data marked with the provided tag will be removed from the cache.
Cache::tags('authors')->flush();
Process Database Records in Chunks with Laravel chunk
Source: https://laravel.com/docs/12.x/queries
This PHP example uses the chunk method from Laravel’s DB facade to process a large number of records in smaller batches. It retrieves users in chunks of 100 and applies a closure to each chunk.
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
DB::table('users')->orderBy('id')->chunk(100, function (Collection $users) {
foreach ($users as $user) {
// ...
}
});
Generate Laravel Dusk Page Object with Artisan Command
Source: https://laravel.com/docs/12.x/dusk
Execute the dusk:page Artisan command to create a new page object class for Laravel Dusk. The generated class will be stored in the tests/Browser/Pages directory, providing a structured way to manage browser interaction logic.
php artisan dusk:page Login
Get difference between Eloquent Collections in PHP
Source: https://laravel.com/docs/12.x/eloquent-collections
The diff method compares the current collection with another provided collection and returns a new collection containing only the models that are present in the original collection but not in the given collection.
use App\Models\User;
$users = $users->diff(User::whereIn('id', [1, 2, 3])->get());
Define Laravel MCP Prompt Response
Source: https://laravel.com/docs/12.x/mcp
This PHP code demonstrates how to create a Laravel MCP prompt that returns an array of Response instances. It shows how to differentiate between assistant and user messages using asAssistant() for AI client interaction, based on a dynamic tone from the request.
<?php
namespace App\Mcp\Prompts;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Prompt;
class DescribeWeatherPrompt extends Prompt
{
/**
* Handle the prompt request.
*
* @return array<int, \Laravel\Mcp\Response>
*/
public function handle(Request $request): array
{
$tone = $request->string('tone');
$systemMessage = "You are a helpful weather assistant. Please provide a weather description in a {$tone} tone.";
$userMessage = "What is the current weather like in New York City?";
return [
Response::text($systemMessage)->asAssistant(),
Response::text($userMessage),
];
}
}
Use Custom Laravel Dusk Browser Macro
Source: https://laravel.com/docs/12.x/dusk
This PHP snippet illustrates how to call a previously defined custom browser macro, scrollToElement, within a Dusk test. It visits a page, scrolls to a specific element identified by its ID, and then asserts that certain text is visible on the page, demonstrating method chaining with the custom macro.
$this->browse(function (Browser $browser) use ($user) {
$browser->visit('/pay')
->scrollToElement('#credit-card-details')
->assertSee('Enter Credit Card Details');
});
Implement Method Injection with Route Parameters in Laravel Controllers with PHP
Source: https://laravel.com/docs/12.x/controllers
This example demonstrates how to combine method injection with route parameters in a Laravel controller. When a controller method expects both injected dependencies (like Request) and route parameters, the route arguments should be listed after the other dependencies. The route definition for PUT /user/{id} is also included to show the full context.
use App\Http\Controllers\UserController;
Route::put('/user/{id}', [UserController::class, 'update']);
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Update the given user.
*/
public function update(Request $request, string $id): RedirectResponse
{
// Update the user...
return redirect('/users');
}
}
Obtain PSR-7 Request Instance in Laravel
Source: https://laravel.com/docs/12.x/requests
After installing the required libraries, you can obtain an instance of a PSR-7 request by type-hinting the ServerRequestInterface in your route closure or controller method. Laravel will automatically convert the incoming request to a PSR-7 compliant object.
use Psr\Http\Message\ServerRequestInterface;
Route::get('/', function (ServerRequestInterface $request) {
// ...
});
Configure Vue Authentication Page Layout
Source: https://laravel.com/docs/12.x/starter-kits
Understand how to change the layout for authentication pages (login, registration) in your Vue starter kit. This involves updating the imported layout component at the top of your application’s resources/js/layouts/AuthLayout.vue file to use ‘simple’, ‘card’, or ‘split’ variants.
import AuthLayout from '@/layouts/auth/AuthSimpleLayout.vue'; // [tl! remove]
import AuthLayout from '@/layouts/auth/AuthSplitLayout.vue'; // [tl! add]
Associate Eloquent Model with Laravel Factory
Source: https://laravel.com/docs/12.x/eloquent-factories
This example shows how to declare the corresponding Eloquent model within a Laravel factory by setting the ‘$model’ property. This linkage ensures the factory knows which model it is responsible for creating.
use App\Administration\Flight;
use Illuminate\Database\Eloquent\Factories\Factory;
class FlightFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var class-string<\Illuminate\Database\Eloquent\Model>
*/
protected $model = Flight::class;
}
Configure Additional Swoole Options in Laravel Octane
Source: https://laravel.com/docs/12.x/octane
This PHP configuration snippet demonstrates how to add optional Swoole-specific settings within your Laravel Octane configuration file. It includes examples for log_file and package_max_length, which are not present by default but can be customized for specific requirements.
'swoole' => [
'options' => [
'log_file' => storage_path('logs/swoole_http.log'),
'package_max_length' => 10 * 1024 * 1024,
],
],
API Singleton Resource: Profile
Source: https://laravel.com/docs/12.x/controllers
Defines routes for a single-instance resource intended for API usage, excluding create and edit views, focusing on show and update operations.
## GET /profile
### Description
Display the specified singleton resource for API consumption.
### Method
GET
### Endpoint
/profile
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **profile** (object) - The profile resource.
#### Response Example
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
}
## PUT/PATCH /profile
### Description
Update the specified singleton resource in storage via API.
### Method
PUT/PATCH
### Endpoint
/profile
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **name** (string) - Required - The new name for the profile.
- **email** (string) - Required - The new email for the profile.
### Request Example
{
"name": "Jane Doe",
"email": "jane.doe@example.com"
}
### Response
#### Success Response (200)
- **message** (string) - Success message.
#### Response Example
{
"message": "Profile updated successfully."
}
Click Link by Display Text with Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
The clickLink method clicks a link on the page using its display text. Dusk automatically injects jQuery if it’s not present on the page, as these methods interact with it.
$browser->clickLink($linkText);
Assert Button Enabled State in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This assertion verifies that a button, specified by its selector, is currently enabled and clickable. It ensures correct button interaction states for user actions.
$browser->assertButtonEnabled($button);
Configure Laravel Broadcasting for SPA with Sanctum (PHP)
Source: https://laravel.com/docs/12.x/sanctum
This PHP configuration snippet shows how to set up Laravel’s broadcasting for a Single Page Application (SPA) within the bootstrap/app.php file. It configures the broadcasting routes with a sanctum authentication guard, ensuring that private/presence channels are authorized via the api middleware and the auth:sanctum guard. This replaces the default channels entry in withRouting to apply specific middleware.
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
// ...
)
->withBroadcasting(
__DIR__.'/../routes/channels.php',
['prefix' => 'api', 'middleware' => ['api', 'auth:sanctum']],
);
Return collection with preserved keys
Source: https://laravel.com/docs/12.x/eloquent-resources
Demonstrates how to return a resource collection while preserving its original keys. This example uses keyBy->id to assign specific keys to the collection items, which are then maintained when UserResource::collection is returned, given that $preserveKeys is set to true in UserResource.
use App\Http\Resources\UserResource;
use App\Models\User;
Route::get('/users', function () {
return UserResource::collection(User::all()->keyBy->id);
});
Laravel Dusk: Selecting a single option from a dropdown
Source: https://laravel.com/docs/12.x/dusk
To interact with <select> elements, the select method is used. It allows you to choose an option by its underlying value, not its display text, and does not require a full CSS selector if a matching name attribute is found.
$browser->select('size', 'Large');
Enable Console Events in Laravel Tests (Pest & PHPUnit)
Source: https://laravel.com/docs/12.x/console-tests
This snippet demonstrates how to enable CommandStarting and CommandFinished console events during testing in Laravel. It utilizes the Illuminate\Foundation\Testing\WithConsoleEvents trait, which must be applied to your test class or used within Pest setup. This allows for testing of event listeners that react to console command lifecycle.
<?php
use Illuminate\Foundation\Testing\WithConsoleEvents;
pest()->use(WithConsoleEvents::class);
// ...
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\WithConsoleEvents;
use Tests\TestCase;
class ConsoleEventTest extends TestCase
{
use WithConsoleEvents;
// ...
}
Laravel Dusk: Unchecking a checkbox input
Source: https://laravel.com/docs/12.x/dusk
To deselect an already checked checkbox, the uncheck method is available. This ensures complete control over checkbox states within your Dusk tests.
$browser->uncheck('terms');
Create Subscribed User Middleware (Laravel)
Source: https://laravel.com/docs/12.x/billing
This PHP class defines a Laravel middleware that enforces subscription requirements for incoming requests. The handle method checks if the authenticated user is subscribed using Cashier’s subscribed() method, redirecting them to a billing page if they are not. This middleware is crucial for protecting routes that require an active subscription.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class Subscribed
{
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next): Response
{
if (! $request->user()?->subscribed()) {
// Redirect user to billing page and ask them to subscribe...
return redirect('/billing');
}
return $next($request);
}
}
Generate Laravel Resource Controller with Model Binding
Source: https://laravel.com/docs/12.x/controllers
Generates a new resource controller (PhotoController) and automatically configures its methods to type-hint a Photo model instance. This simplifies route model binding within the controller methods.
php artisan make:controller PhotoController --model=Photo --resource
Configure Automatic Default Seeding in Laravel Tests
Source: https://laravel.com/docs/12.x/database-testing
Illustrates how to instruct Laravel to automatically run the default DatabaseSeeder before each test that uses the RefreshDatabase trait. This is achieved by setting the $seed property to true in your base TestCase class, streamlining test setup.
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
/**
*
* Indicates whether the default seeder should run before each test.
*
* @var bool
*/
protected $seed = true;
}
Laravel PHP: Use Closure for Dynamic Missing Argument Prompt
Source: https://laravel.com/docs/12.x/artisan
This PHP example demonstrates advanced customization of missing argument prompts using a closure. It leverages Laravel\Prompts\search to provide a dynamic search interface for selecting a user, offering complete control over the prompting logic.
use App\Models\User;
use function Laravel\Prompts\search;
// ...
return [
'user' => fn () => search(
label: 'Search for a user:',
placeholder: 'E.g. Taylor Otwell',
options: fn ($value) => strlen($value) > 0
? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
: []
),
];
Assert Element Visibility in Laravel Dusk
Source: https://laravel.com/docs/12.x/dusk
This method asserts that an element matching the provided CSS selector is currently visible on the page. It helps confirm that UI components are rendered as expected and are not hidden.
$browser->assertVisible($selector);
Retrieve a Single Context Value (Laravel PHP)
Source: https://laravel.com/docs/12.x/context
This snippet demonstrates how to retrieve a single value from the Laravel context using the get method of the Context facade. It takes a key as an argument and returns the associated value.
use Illuminate\Support\Facades\Context;
$value = Context::get('key');
Integrate Laravel Job Batches into a Job Chain (PHP)
Source: https://laravel.com/docs/12.x/queues
This example shows how to embed job batches within a Laravel job chain. It defines a sequence where a FlushPodcastCache job runs first, followed by a batch of ReleasePodcast jobs, and then another batch of SendPodcastReleaseNotification jobs.
use App\Jobs\FlushPodcastCache;
use App\Jobs\ReleasePodcast;
use App\Jobs\SendPodcastReleaseNotification;
use Illuminate\Support\Facades\Bus;
Bus::chain([
new FlushPodcastCache,
Bus::batch([
new ReleasePodcast(1),
new ReleasePodcast(2),
]),
Bus::batch([
new SendPodcastReleaseNotification(1),
new SendPodcastReleaseNotification(2),
]),
])->dispatch();
Get median value from collection (Laravel PHP)
Source: https://laravel.com/docs/12.x/collections
The median method calculates and returns the median value of a given key within the collection. It can also compute the median for a collection of simple numeric values.
$median = collect([
['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]
])->median('foo');
// 15
$median = collect([1, 1, 2, 4])->median();
// 1.5
Publish Package Views for Customization in Laravel (PHP)
Source: https://laravel.com/docs/12.x/packages
Enable users to override your package’s views by making them publishable to the application’s resources/views/vendor directory. Utilize the service provider’s publishes method in the boot method, providing an array of source view paths and their desired publish locations.
/**
* Bootstrap the package services.
*/
public function boot(): void
{
$this->loadViewsFrom(__DIR__.'/../resources/views', 'courier');
$this->publishes([
__DIR__.'/../resources/views' => resource_path('views/vendor/courier'),
]);
}
Accessing Request and Route Parameters in a Controller in Laravel
Source: https://laravel.com/docs/12.x/requests
This PHP example demonstrates how to inject both the Illuminate\Http\Request instance and a route parameter (id) into a controller method (update). It is important to list route parameters after other dependencies like the request object.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Update the specified user.
*/
public function update(Request $request, string $id): RedirectResponse
{
// Update the user...
return redirect('/users');
}
}
Implement Basic Laravel Prompts multisearch Function
Source: https://laravel.com/docs/12.x/prompts
Shows the basic usage of the multisearch function from Laravel Prompts to allow users to select multiple items from a searchable list. It utilizes a closure to dynamically filter user options based on input and returns an array of selected IDs.
use function Laravel\Prompts\multisearch;
$ids = multisearch(
'Search for the users that should receive the mail',
fn (string $value) => strlen($value) > 0
? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
: []
);
Load Vite Assets in Laravel Blade Templates
Source: https://laravel.com/docs/12.x/vite
This section demonstrates various ways to use the @vite Blade directive to include CSS and JavaScript assets in a Laravel application. The directive intelligently detects the Vite development server for HMR or loads compiled and versioned assets in production. Examples include loading multiple entry points, a single JavaScript entry point, and specifying a custom build path.
<!DOCTYPE html>
<head>
{{-- ... --}}
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<!DOCTYPE html>
<head>
{{-- ... --}}
@vite('resources/js/app.js')
</head>
<!doctype html>
<head>
{{-- Given build path is relative to public path. --}}
@vite('resources/js/app.js', 'vendor/courier/build')
</head>
Assert query string parameter presence in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the given query string parameter is present, optionally with a specific value. This method allows checking for the existence and value of URL query parameters.
$browser->assertQueryStringHas($name);
$browser->assertQueryStringHas($name, $value);
Inject Specific Storage Disk with Laravel Storage Attribute
Source: https://laravel.com/docs/12.x/container
This PHP example demonstrates how to use the #[Storage('local')] attribute in a Laravel controller’s constructor. It injects a specific filesystem disk (e.g., ‘local’) into the Filesystem contract, simplifying driver-based dependency injection without manual binding.
<?php
namespace App\Http\Controllers;
use Illuminate\Container\Attributes\Storage;
use Illuminate\Contracts\Filesystem\Filesystem;
class PhotoController extends Controller
{
public function __construct(
#[Storage('local')] protected Filesystem $filesystem
) {
// ...
}
}
Check Past Due Subscription Status (PHP)
Source: https://laravel.com/docs/12.x/cashier-paddle
Verifies if a user’s subscription is in a ‘past_due’ state, typically due to a failed payment. Subscriptions in this state are not active until payment information is updated.
if ($user->subscription()->pastDue()) {
// ...
}
Iterate over Eloquent Collection in PHP
Source: https://laravel.com/docs/12.x/eloquent-collections
Eloquent collections serve as iterators, allowing you to loop over them using a foreach construct, similar to how you would iterate over a simple PHP array. This example fetches active users and prints their names.
use App\Models\User;
$users = User::where('active', 1)->get();
foreach ($users as $user) {
echo $user->name;
}
Return multiple content responses from Laravel MCP tool
Source: https://laravel.com/docs/12.x/mcp
This PHP example demonstrates how a Laravel MCP tool can return several distinct pieces of content simultaneously. The handle method returns an array of Response instances, each created with Response::text(), allowing for the organized delivery of various data points to the client.
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
/**
* Handle the tool request.
*
* @return array<int, \Laravel\Mcp\Response>
*/
public function handle(Request $request): array
{
// ...
return [
Response::text('Weather Summary: Sunny, 72°F'),
Response::text('**Detailed Forecast**\n- Morning: 65°F\n- Afternoon: 78°F\n- Evening: 70°F')
];
}
Run Composer Commands via Laravel Sail
Source: https://laravel.com/docs/12.x/sail
Use the sail composer prefix to execute Composer commands within the Laravel Sail Docker container, leveraging its built-in Composer installation for dependency management.
sail composer require laravel/sanctum
Use Laravel Prompts for basic single-choice selection
Source: https://laravel.com/docs/12.x/prompts
Demonstrates the basic usage of the select function in Laravel Prompts to allow a user to choose one option from a predefined list. It imports the select function and defines a label and an array of options to present to the user.
use function Laravel\Prompts\select;
$role = select(
label: 'What role should the user have?',
options: ['Member', 'Contributor', 'Owner']
);
Laravel Group Routes with Shared Middleware
Source: https://laravel.com/docs/12.x/routing
This PHP example shows how to apply common middleware to a group of routes in Laravel. The middleware method defines an array of middleware that will be executed for all routes defined within the group’s closure.
Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// Uses first & second middleware...
});
Route::get('/user/profile', function () {
// Uses first & second middleware...
});
});
Define Price-Specific Tax Rates for Subscriptions in Laravel Cashier
Source: https://laravel.com/docs/12.x/billing
This PHP method allows defining different Stripe tax rates for individual subscription prices. It should be implemented on your billable model to support subscriptions with multiple products, each potentially having varied tax requirements.
/**
* The tax rates that should apply to the customer's subscriptions.
*
* @return array<string, array<int, string>>
*/
public function priceTaxRates(): array
{
return [
'price_monthly' => ['txr_id'],
];
}
Define JavaScript and CSS compilation with Laravel Mix
Source: https://laravel.com/docs/12.x/mix
This example shows how to use Laravel Mix’s fluent API to compile JavaScript and PostCSS assets. It takes an input JavaScript file from ‘resources/js’ and an input CSS file from ‘resources/css’, then outputs the processed files to ‘public/js’ and ‘public/css’ respectively.
mix.js('resources/js/app.js', 'public/js').postCss('resources/css/app.css', 'public/css');
Assert text is not present within selector in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the given text is not present within the specified CSS selector. This ensures a string does not appear within a particular element.
$browser->assertDontSeeIn($selector, $text);
Render Basic Inline Checkout with Blade Component
Source: https://laravel.com/docs/12.x/cashier-paddle
This Blade component renders an inline Paddle checkout widget. It requires a checkout session generated by Cashier. The class attribute allows for styling the container of the inline widget.
<x-paddle-checkout :checkout="$checkout" class="w-full" />
Dispatch a Queueable Laravel Notification
Source: https://laravel.com/docs/12.x/notifications
This PHP example shows how to dispatch a notification that has been configured for queueing. Laravel automatically detects the ShouldQueue interface on the class and places the notification delivery onto the configured queue for asynchronous processing.
$user->notify(new InvoicePaid($invoice));
Create Process Pipeline with Array of Commands in Laravel
Source: https://laravel.com/docs/12.x/processes
For simpler pipelines without the need for individual process customization, the pipe method can directly accept an array of command strings. This provides a concise way to chain commands.
$result = Process::pipe([
'cat example.txt',
'grep -i "laravel"',
]);
Use a Laravel Dusk component in Pest and PHPUnit tests
Source: https://laravel.com/docs/12.x/dusk
This demonstrates how to integrate a predefined Laravel Dusk component, such as a DatePicker, into both Pest and PHPUnit browser tests. By calling the component’s encapsulated methods within a within block, tests remain clean and adaptable, easily managing UI interactions across different testing frameworks.
<?php
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\Browser\Components\DatePicker;
pest()->use(DatabaseMigrations::class);
test('basic example', function () {
$this->browse(function (Browser $browser) {
$browser->visit('/')
->within(new DatePicker, function (Browser $browser) {
$browser->selectDate(2019, 1, 30);
})
->assertSee('January');
});
});
<?php
namespace Tests\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\Browser\Components\DatePicker;
use Tests\DuskTestCase;
class ExampleTest extends DuskTestCase
{
/**
* A basic component test example.
*/
public function test_basic_example(): void
{
$this->browse(function (Browser $browser) {
$browser->visit('/')
->within(new DatePicker, function (Browser $browser) {
$browser->selectDate(2019, 1, 30);
})
->assertSee('January');
});
}
}
Paginate Eloquent Results with Where Clauses in Laravel
Source: https://laravel.com/docs/12.x/pagination
This example shows how to apply pagination to Eloquent models after filtering them with where clauses. The paginate method is chained after the where condition to retrieve 15 records per page that meet the specified criteria.
$users = User::where('votes', '>', 100)->paginate(15);
Get Length of Laravel Str (PHP)
Source: https://laravel.com/docs/12.x/strings
The length method returns the character count of the given string. This is a fundamental utility for various string processing tasks, such as validation or display limits.
use Illuminate\Support\Str;
$length = Str::of('Laravel')->length();
// 7
Assert text is present within selector in PHP
Source: https://laravel.com/docs/12.x/dusk
Assert that the given text is present within the specified CSS selector. This allows for more targeted text verification within specific elements.
$browser->assertSeeIn($selector, $text);
Check if Subscribed to a Specific Price in Laravel
Source: https://laravel.com/docs/12.x/billing
This code illustrates using the ‘subscribedToPrice’ method to check if a customer’s subscription corresponds to a particular Stripe price ID. This is useful for verifying the exact pricing plan a user is on.
if ($user->subscribedToPrice('price_basic_monthly', 'default')) {
// ...
}
Create a Device Authorization Grant Client via Artisan
Source: https://laravel.com/docs/12.x/passport
This shell command creates a new first-party device flow enabled client using the passport:client Artisan command. The --device option ensures the client is configured for the device authorization grant, providing a client ID and secret for token issuance.
php artisan passport:client --device
Prêt à passer à la suite ?
Vous avez terminé cette leçon sur Install Paratest and run Laravel tests in parallel. Continuez votre apprentissage avec la prochaine leçon ou explorez d'autres formations.