================ CODE SNIPPETS ================ TITLE: Setup and Run Laravel Development Server DESCRIPTION: Navigates into the new application directory, installs frontend dependencies, builds assets, and starts the Laravel development server. SOURCE: https://laravel.com/docs/12.x/starter-kits LANGUAGE: shell CODE: ``` cd my-app npm install && npm run build composer run dev ``` -------------------------------- TITLE: Database Connection URL Examples DESCRIPTION: Examples of database URLs used for configuring connections. These URLs typically follow a schema like 'driver://username:password@host:port/database?options'. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: plaintext CODE: ``` 1mysql://root:password@127.0.0.1/forge?charset=UTF-8 mysql://root:password@127.0.0.1/forge?charset=UTF-8 ``` LANGUAGE: plaintext CODE: ``` 1driver://username:password@host:port/database?options driver://username:password@host:port/database?options ``` -------------------------------- TITLE: Start Vagrant Virtual Machine DESCRIPTION: Command to start the Vagrant virtual machine for the Homestead environment. This command regenerates the virtual machine to utilize the latest Vagrant installation. SOURCE: https://laravel.com/docs/12.x/homestead LANGUAGE: bash CODE: ``` vagrant up ``` -------------------------------- TITLE: Listen for Query Execution Events in Laravel DESCRIPTION: Provides an example of how to register a listener for all SQL queries executed by the application using the DB::listen method. This is useful for logging or debugging queries. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` sql; // $query->bindings; // $query->time; // $query->toRawSql(); }); } } ``` -------------------------------- TITLE: Install Paratest for Parallel Testing DESCRIPTION: Installs the `brianium/paratest` Composer package as a development dependency, enabling parallel test execution. This significantly speeds up test runs by utilizing multiple CPU cores. Requires Composer. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: shell CODE: ``` composer require brianium/paratest --dev ``` -------------------------------- TITLE: Run Laravel Development Server DESCRIPTION: Navigates into the application directory, installs frontend dependencies, builds assets, and starts the local development server using Composer scripts. The application will be accessible at http://localhost:8000. SOURCE: https://laravel.com/docs/12 LANGUAGE: bash CODE: ``` cd example-app npm install && npm run build composer run dev ``` -------------------------------- TITLE: Laravel Read/Write Database Connections Configuration DESCRIPTION: Example of configuring separate read and write database connections in Laravel. This allows specifying different hosts for read and write operations and controlling sticky read behavior. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` 1'mysql' => [ 2 'read' => [ 3 'host' => [ 4 '192.168.1.1', 5 '196.168.1.2', 6 ], 7 ], 8 'write' => [ 9 'host' => [ 10 '196.168.1.3', 11 ], 12 ], 13 'sticky' => true, 14  15 'database' => env('DB_DATABASE', 'laravel'), 16 'username' => env('DB_USERNAME', 'root'), 17 'password' => env('DB_PASSWORD', ''), 18 'unix_socket' => env('DB_SOCKET', ''), 19 'charset' => env('DB_CHARSET', 'utf8mb4'), 20 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'), 21 'prefix' => '', 22 'prefix_indexes' => true, 23 'strict' => true, 24 'engine' => null, 25 'options' => extension_loaded('pdo_mysql') ? array_filter([ 26 PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), 27 ]) : [], 28], ``` LANGUAGE: php CODE: ``` 'mysql' => [ 'read' => [ 'host' => [ '192.168.1.1', '196.168.1.2', ], ], 'write' => [ 'host' => [ '196.168.1.3', ], ], 'sticky' => true, 'database' => env('DB_DATABASE', 'laravel'), 'username' => env('DB_USERNAME', 'root'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => env('DB_CHARSET', 'utf8mb4'), 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'), 'prefix' => '', 'prefix_indexes' => true, 'strict' => true, 'engine' => null, 'options' => extension_loaded('pdo_mysql') ? array_filter([ PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), ]) : [], ] ``` -------------------------------- TITLE: Clone Homestead Repository DESCRIPTION: Clones the Laravel Homestead repository to the specified directory. This is the initial step for installing Homestead. SOURCE: https://laravel.com/docs/12.x/homestead LANGUAGE: bash CODE: ``` git clone https://github.com/laravel/homestead.git ~/Homestead ``` -------------------------------- TITLE: Installation and Configuration DESCRIPTION: Guides on installing and configuring Laravel Passport, including deploying, upgrading, managing token lifetimes, and overriding default models or routes. SOURCE: https://laravel.com/docs/12.x/passport LANGUAGE: APIDOC CODE: ``` ## Installation and Configuration ### Installation - **Deploying Passport:** Instructions for deploying Passport to your application. - **Upgrading Passport:** Guidance on upgrading to newer versions of Passport. ### Configuration - **Token Lifetimes:** Configure the expiration times for access tokens and refresh tokens. - **Overriding Default Models:** Customize the Passport models used by the package. - **Overriding Routes:** Modify or extend the default routes provided by Passport. ``` -------------------------------- TITLE: Run PHPUnit Tests (Laravel) DESCRIPTION: Executes all tests written using the PHPUnit testing framework within a Laravel project. Requires PHPUnit to be installed and configured. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: shell CODE: ``` ./vendor/bin/phpunit ``` -------------------------------- TITLE: Run Pest Tests (Laravel) DESCRIPTION: Executes all tests written using the Pest testing framework within a Laravel project. Requires Pest to be installed and configured. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: shell CODE: ``` ./vendor/bin/pest ``` -------------------------------- TITLE: Run Laravel Tests with Pest, PHPUnit, or Artisan DESCRIPTION: Execute your application's tests using the command line. This includes options for running tests with Pest, PHPUnit, or the Artisan command. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: bash CODE: ``` vendor/bin/pest vendor/bin/phpunit php artisan test ``` -------------------------------- TITLE: Laravel Parallel Testing Hooks (PHP) DESCRIPTION: Define setup and teardown logic for parallel test processes and test cases using the ParallelTesting facade. This allows for resource preparation and cleanup across multiple testing environments. It supports setting up processes, individual test cases, and test databases, as well as tearing down test cases and processes. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: php CODE: ``` select(/* ... */); ``` LANGUAGE: php CODE: ``` $pdo = DB::connection()->getPdo(); ``` -------------------------------- TITLE: Run General SQL Statement DESCRIPTION: Executes a general SQL statement that does not return a value, such as dropping a table, using the `statement` method. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` DB::statement('drop table users'); ``` -------------------------------- TITLE: Basic PHPUnit Test Example DESCRIPTION: A basic unit test class structure using PHPUnit, a popular testing framework for PHP. It includes a simple test method that asserts `true`. Requires PHPUnit and PHP. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: php CODE: ``` assertTrue(true); } } ``` -------------------------------- TITLE: Create and Run a New Laravel Application DESCRIPTION: Creates a new Laravel application named 'example-app' and then installs frontend dependencies and runs the development server using Composer scripts. SOURCE: https://laravel.com/docs/index LANGUAGE: bash CODE: ``` laravel new example-app cd example-app npm install && npm run build composer run dev ``` -------------------------------- TITLE: Manually Install Laravel Reverb DESCRIPTION: Installs the Laravel Reverb package using Composer. After installation, a command is used to publish configuration and enable broadcasting. SOURCE: https://laravel.com/docs/broadcasting LANGUAGE: bash CODE: ``` composer require laravel/reverb ``` LANGUAGE: bash CODE: ``` php artisan reverb:install ``` -------------------------------- TITLE: Create a New Laravel Application DESCRIPTION: Creates a new Laravel application named 'example-app' using the Laravel installer. This command will prompt for framework, database, and starter kit preferences. SOURCE: https://laravel.com/docs/12 LANGUAGE: bash CODE: ``` laravel new example-app ``` -------------------------------- TITLE: Basic Pest Test Example DESCRIPTION: A simple test case written using Pest, a testing framework for PHP. It asserts that the boolean value `true` is indeed `true`. Requires Pest and PHP. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: php CODE: ``` toBeTrue(); }); ``` -------------------------------- TITLE: Create Unit Test (Laravel) DESCRIPTION: Generates a new unit test file using the `make:test` Artisan command with the `--unit` option. Tests are placed in the `tests/Unit` directory. Requires the Laravel framework. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: shell CODE: ``` php artisan make:test UserTest --unit ``` -------------------------------- TITLE: Install Telescope Assets and Run Migrations DESCRIPTION: After installing Telescope, these Artisan commands publish its assets and create the necessary database tables. SOURCE: https://laravel.com/docs/12.x/telescope LANGUAGE: bash CODE: ``` php artisan telescope:install php artisan migrate ``` -------------------------------- TITLE: Run SELECT Query with Named Bindings DESCRIPTION: Executes a SQL SELECT query using named bindings instead of question marks for parameter placeholders, enhancing readability. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` $results = DB::select('select * from users where id = :id', ['id' => 1]); ``` -------------------------------- TITLE: Manually Manage Database Transactions DESCRIPTION: This section covers the manual control of database transactions in Laravel using the `DB` facade. It shows how to explicitly start a transaction with `beginTransaction`, revert changes with `rollBack`, and finalize operations with `commit`. This approach provides granular control over transaction lifecycles, suitable for complex scenarios. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` use Illuminate\Support\Facades\DB; DB::beginTransaction(); ``` LANGUAGE: php CODE: ``` DB::rollBack(); ``` LANGUAGE: php CODE: ``` DB::commit(); ``` -------------------------------- TITLE: Configure SQLite Database Connection - Laravel DESCRIPTION: Specifies the database connection type and path for SQLite in Laravel's environment configuration. This is essential for applications using SQLite as their primary database. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: dotenv CODE: ``` DB_CONNECTION=sqlite DB_DATABASE=/absolute/path/to/database.sqlite ``` -------------------------------- TITLE: Install Laravel Homestead Per Project DESCRIPTION: Install Homestead as a development dependency in your Laravel project using Composer. This enables a dedicated Homestead environment for each project. SOURCE: https://laravel.com/docs/12.x/homestead LANGUAGE: bash CODE: ``` composer require laravel/homestead --dev ``` -------------------------------- TITLE: Install Dusk and ChromeDriver DESCRIPTION: Installs Dusk and its required ChromeDriver binary using the Artisan command. SOURCE: https://laravel.com/docs/12.x/dusk LANGUAGE: bash CODE: ``` php artisan dusk:install ``` -------------------------------- TITLE: Installation DESCRIPTION: Install Laravel Fortify using Composer and publish its resources. SOURCE: https://laravel.com/docs/12.x/fortify LANGUAGE: APIDOC CODE: ``` ## Installation ### Description Install Laravel Fortify using the Composer package manager and then publish Fortify's resources using the `fortify:install` Artisan command. ### Method `composer require laravel/fortify` `php artisan fortify:install` `php artisan migrate` ### Parameters None ### Request Example None ### Response #### Success Response (200) Fortify's actions, configuration file, and migrations are published. Database is migrated. #### Response Example None ``` -------------------------------- TITLE: Create Laravel App with Community Starter Kit DESCRIPTION: Demonstrates how to create a new Laravel application using a specific community-maintained starter kit from Packagist via the Laravel installer. SOURCE: https://laravel.com/docs/12.x/starter-kits LANGUAGE: bash CODE: ``` laravel new my-app --using=example/starter-kit ``` -------------------------------- TITLE: Run Specific Laravel Test Suite DESCRIPTION: Executes tests belonging to a specific test suite (e.g., 'Feature') using the `test` Artisan command with the `--testsuite` option. Also includes the `--stop-on-failure` flag to halt execution upon the first failed test. Requires the Laravel framework. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: shell CODE: ``` php artisan test --testsuite=Feature --stop-on-failure ``` -------------------------------- TITLE: Update Laravel Installer via Composer DESCRIPTION: Command to update the Laravel installer globally using Composer. This ensures compatibility with newer Laravel versions and starter kits. SOURCE: https://laravel.com/docs/12.x/upgrade LANGUAGE: bash CODE: ``` composer global update laravel/installer ``` -------------------------------- TITLE: Run INSERT Statement in Laravel DESCRIPTION: Inserts a new record into the 'users' table using the `insert` method with parameter binding for security. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` use Illuminate\Support\Facades\DB; DB::insert('insert into users (id, name) values (?, ?)', [1, 'Marc']); ``` -------------------------------- TITLE: Inspect Database Schema with Laravel Facade DESCRIPTION: Uses the Schema facade to retrieve database schema information programmatically. It can fetch tables, views, columns, indexes, and foreign keys for default or specified connections. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` use Illuminate\Support\Facades\Schema; $tables = Schema::getTables(); $views = Schema::getViews(); $columns = Schema::getColumns('users'); $indexes = Schema::getIndexes('users'); $foreignKeys = Schema::getForeignKeys('users'); ``` LANGUAGE: php CODE: ``` $columns = Schema::connection('sqlite')->getColumns('users'); ``` -------------------------------- TITLE: Create and Open New Laravel App with Herd (Windows) DESCRIPTION: Shows how to create a new Laravel application and open it in the browser using the Herd development environment on Windows via PowerShell. Assumes Herd is installed and configured. SOURCE: https://laravel.com/docs/index LANGUAGE: powershell CODE: ``` cd ")\Herd laravel new my-app cd my-app herd open ``` -------------------------------- TITLE: Run Laravel Tests via Artisan DESCRIPTION: Executes all tests within a Laravel project using the `test` Artisan command. This command acts as a unified runner for Pest or PHPUnit tests. Requires the Laravel framework. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: shell CODE: ``` php artisan test ``` -------------------------------- TITLE: Monitor Database Connections with Artisan and Events DESCRIPTION: The `db:monitor` command dispatches an `Illuminate\Database\Events\DatabaseBusy` event if connection counts exceed a specified threshold. This event can be listened for in `AppServiceProvider` to trigger notifications. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` php artisan db:monitor --databases=mysql,pgsql --max=100 ``` LANGUAGE: php CODE: ``` use App\Notifications\DatabaseApproachingMaxConnections; use Illuminate\Database\Events\DatabaseBusy; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Notification; /** * Bootstrap any application services. */ public function boot(): void { Event::listen(function (DatabaseBusy $event) { Notification::route('mail', 'dev@example.com') ->notify(new DatabaseApproachingMaxConnections( $event->connectionName, $event->connections )); }); } ``` -------------------------------- TITLE: Retrieve All Users and Access Properties DESCRIPTION: Fetches all records from the 'users' table and iterates through the results, accessing the 'name' property of each user object. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` use Illuminate\Support\Facades\DB; $users = DB::select('select * from users'); foreach ($users as $user) { echo $user->name; } ``` -------------------------------- TITLE: Install Laravel Dusk DESCRIPTION: Installs the Laravel Dusk package as a development dependency using Composer. SOURCE: https://laravel.com/docs/12.x/dusk LANGUAGE: bash CODE: ``` composer require laravel/dusk --dev ``` -------------------------------- TITLE: Install and Configure Valet DESCRIPTION: Executes the Valet installation script, which configures Nginx and DnsMasq for local development. It also sets up Valet to launch automatically on system startup. SOURCE: https://laravel.com/docs/12.x/valet LANGUAGE: shell CODE: ``` valet install ``` -------------------------------- TITLE: Execute Unprepared SQL Statements in Laravel DESCRIPTION: Demonstrates how to execute raw SQL statements without binding parameters using Laravel's DB facade. This method is useful for simple queries but carries a risk of SQL injection if user input is not properly sanitized. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` DB::unprepared('update users set votes = 100 where name = "Dries"'); ``` -------------------------------- TITLE: Generate Homestead Configuration Files DESCRIPTION: Generate the necessary `Vagrantfile` and `Homestead.yaml` files for a per-project Homestead installation using the Homestead CLI. This command automatically configures initial site and folder directives. SOURCE: https://laravel.com/docs/12.x/homestead LANGUAGE: bash CODE: ``` # macOS / Linux... php vendor/bin/homestead make # Windows... vendor\\bin\\homestead make ``` -------------------------------- TITLE: Install Packages Non-interactively in Homestead Customizations DESCRIPTION: Prevent package installation prompts during Homestead customization by using specific `apt-get` options. This ensures unattended updates and avoids overwriting existing configurations. SOURCE: https://laravel.com/docs/12.x/homestead LANGUAGE: bash CODE: ``` sudo apt-get -y \ -o Dpkg::Options::="--force-confdef" \ -o Dpkg::Options::="--force-confold" \ install package-name ``` -------------------------------- TITLE: Run Laravel Tests with Coverage (Shell) DESCRIPTION: Generate test coverage reports by running tests with the --coverage option. This requires Xdebug or PCOV and helps determine the extent to which application code is exercised by the test suite. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: bash CODE: ``` php artisan test --coverage ``` -------------------------------- TITLE: Install Horizon Assets DESCRIPTION: Publishes Horizon's assets using the `horizon:install` Artisan command. SOURCE: https://laravel.com/docs/12.x/horizon LANGUAGE: bash CODE: ``` php artisan horizon:install ``` -------------------------------- TITLE: Install Laravel Installer via Composer DESCRIPTION: Installs the Laravel installer globally using Composer. This command assumes you already have Composer installed. SOURCE: https://laravel.com/docs/12 LANGUAGE: bash CODE: ``` composer global require laravel/installer ``` -------------------------------- TITLE: Laravel PHPDoc Example with Attributes DESCRIPTION: Demonstrates a valid Laravel documentation block with `@param` and `@return` attributes, including types and descriptions. It shows the required spacing for attributes and the handling of exceptions. This format is used for documenting methods and their parameters/return values. SOURCE: https://laravel.com/docs/12.x/contributions LANGUAGE: php CODE: ``` /** * 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) { // ... } ``` LANGUAGE: php CODE: ``` /** * 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) { // ... } ``` -------------------------------- TITLE: Travis CI Configuration for Laravel Dusk DESCRIPTION: This configuration enables running Laravel Dusk tests on Travis CI. It sets up PHP, installs dependencies, generates an application key, downloads the Chrome driver, and starts headless Chrome and the PHP development server before executing Dusk tests. SOURCE: https://laravel.com/docs/12.x/dusk LANGUAGE: yaml CODE: ``` 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 ``` -------------------------------- TITLE: Create New Laravel Application DESCRIPTION: Creates a new Laravel application using the Laravel installer CLI, allowing selection of a preferred starter kit. SOURCE: https://laravel.com/docs/12.x/starter-kits LANGUAGE: shell CODE: ``` laravel new my-app ``` -------------------------------- TITLE: Install Laravel Reverb (Composer) DESCRIPTION: Manually installs the Laravel Reverb package using Composer. This is an alternative to using the Artisan command for setup. SOURCE: https://laravel.com/docs/12.x/broadcasting LANGUAGE: shell CODE: ``` composer require laravel/reverb ``` -------------------------------- TITLE: Run Basic SELECT Query in Laravel DESCRIPTION: Executes a basic SQL SELECT query with parameter binding to fetch user data. Protects against SQL injection and returns results as an array of stdClass objects. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` $users]); } } ``` -------------------------------- TITLE: Configure Xdebug Autostart for Web Requests DESCRIPTION: Enables Xdebug to automatically start debugging for web requests by modifying the Xdebug configuration file within the Homestead VM. Requires `xdebug.client_host` and `xdebug.mode` to be set. SOURCE: https://laravel.com/docs/12.x/homestead LANGUAGE: ini CODE: ``` 1; If Homestead.yaml contains a different subnet for the IP address, this address may be different... 2xdebug.client_host = 192.168.10.1 3xdebug.mode = debug 4xdebug.start_with_request = yes ; 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 ``` -------------------------------- TITLE: GitHub Actions Workflow for Laravel Dusk Tests DESCRIPTION: This GitHub Actions workflow automates the execution of Laravel Dusk tests. It checks out the code, prepares the environment, creates a database, installs Composer dependencies, generates an application key, updates the Chrome driver, and starts the Chrome driver and Laravel server. It also includes steps to upload screenshots and console logs on failure. SOURCE: https://laravel.com/docs/12.x/dusk LANGUAGE: yaml CODE: ``` 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@v4 - 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 ``` -------------------------------- TITLE: Initialize Homestead Environment (Windows) DESCRIPTION: This script initializes the Homestead environment on Windows systems. SOURCE: https://laravel.com/docs/12.x/homestead LANGUAGE: batch CODE: ``` init.bat ``` -------------------------------- TITLE: Run Laravel Development Server with Inertia SSR DESCRIPTION: Explains the composer command to start the Laravel development server and Inertia SSR server after building an SSR compatible bundle. SOURCE: https://laravel.com/docs/12.x/starter-kits LANGUAGE: bash CODE: ``` composer dev:ssr ``` -------------------------------- TITLE: Programmatic Channel Management in Vue DESCRIPTION: Provides an example of using the `useEcho` hook in Vue to get functions for manual control over channel subscriptions, such as stopping, starting, or leaving channels. SOURCE: https://laravel.com/docs/12.x/broadcasting LANGUAGE: typescript CODE: ``` ``` -------------------------------- TITLE: Start Reverb Server with Custom Host and Port DESCRIPTION: Starts the Reverb server on a specified host and port using command-line options. This allows customization of the server's network binding. SOURCE: https://laravel.com/docs/12.x/reverb LANGUAGE: bash CODE: ``` php artisan reverb:start --host=127.0.0.1 --port=9000 ``` -------------------------------- TITLE: Create Feature Test (Laravel) DESCRIPTION: Generates a new feature test file using the `make:test` Artisan command. Tests are placed in the `tests/Feature` directory by default. Requires the Laravel framework. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: shell CODE: ``` php artisan make:test UserTest ``` -------------------------------- TITLE: Install spatie/fork for Concurrency DESCRIPTION: Installs the spatie/fork package, which is required for using the 'fork' driver in Laravel's Concurrency facade for improved performance in CLI contexts. SOURCE: https://laravel.com/docs/12.x/concurrency LANGUAGE: bash CODE: ``` composer require spatie/fork ``` -------------------------------- TITLE: Retrieve Multiple Result Sets DESCRIPTION: Executes a stored procedure that returns multiple result sets and retrieves them using the `selectResultSets` method. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` [$options, $notifications] = DB::selectResultSets( "CALL get_user_options_and_notifications(?)", $request->user()->id ); ``` -------------------------------- TITLE: Install Laravel Horizon DESCRIPTION: Installs the Laravel Horizon package into your project using Composer. SOURCE: https://laravel.com/docs/12.x/horizon LANGUAGE: bash CODE: ``` composer require laravel/horizon ``` -------------------------------- TITLE: Publish Fortify Resources DESCRIPTION: Publishes Fortify's actions, service provider, configuration file, and database migrations using the `fortify:install` Artisan command. This sets up the necessary files for Fortify's functionality. SOURCE: https://laravel.com/docs/12.x/fortify LANGUAGE: shell CODE: ``` php artisan fortify:install ``` -------------------------------- TITLE: Start Laravel and Vite Development Servers DESCRIPTION: This command starts both the Laravel development server and the Vite development server simultaneously, typically used for local development. SOURCE: https://laravel.com/docs/12.x/vite LANGUAGE: bash CODE: ``` composer run dev ``` -------------------------------- TITLE: Use Published shadcn/ui Switch Component DESCRIPTION: Example of how to import and use the Switch component from shadcn/ui within a React page. Assumes the component was published to the correct path. SOURCE: https://laravel.com/docs/12.x/starter-kits LANGUAGE: jsx CODE: ``` import { Switch } from "@/components/ui/switch" const MyPage = () => { return (
); }; export default MyPage; ``` -------------------------------- TITLE: Recreate Test Databases for Parallel Runs DESCRIPTION: Forces the recreation of test databases for parallel test execution using the `--recreate-databases` option with the `test` Artisan command. This ensures a clean state for each parallel run, which can be useful for isolating test environments. Requires a configured database connection and `paratest`. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: shell CODE: ``` php artisan test --parallel --recreate-databases ``` -------------------------------- TITLE: Disable Foreign Key Constraints for SQLite - Laravel DESCRIPTION: Demonstrates how to disable foreign key constraints for SQLite connections within Laravel's environment configuration. Useful for specific database setups where constraints are not needed or managed differently. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: dotenv CODE: ``` DB_FOREIGN_KEYS=false ``` -------------------------------- TITLE: Add shadcn/ui Component DESCRIPTION: Command to publish a shadcn/ui component to your React project. This makes the component available for use within your application. SOURCE: https://laravel.com/docs/12.x/starter-kits LANGUAGE: bash CODE: ``` npx shadcn@latest add switch ``` -------------------------------- TITLE: Install Laravel Passport API DESCRIPTION: Installs Laravel Passport and its necessary database migrations and encryption keys. SOURCE: https://laravel.com/docs/12.x/passport LANGUAGE: bash CODE: ``` php artisan install:api --passport ``` -------------------------------- TITLE: Initialize Homestead Environment (macOS/Linux) DESCRIPTION: This script initializes the Homestead environment on macOS and Linux systems. SOURCE: https://laravel.com/docs/12.x/homestead LANGUAGE: bash CODE: ``` bash init.sh ``` -------------------------------- TITLE: Run DELETE Statement in Laravel DESCRIPTION: Deletes all records from the 'users' table using the `delete` method and returns the count of deleted rows. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` use Illuminate\Support\Facades\DB; $deleted = DB::delete('delete from users'); ``` -------------------------------- TITLE: Install Flysystem SFTP Driver DESCRIPTION: Installs the Flysystem SFTP v3 package using Composer, a prerequisite for using the SFTP driver in Laravel. SOURCE: https://laravel.com/docs/12.x/filesystem LANGUAGE: bash CODE: ``` composer require league/flysystem-sftp-v3 "^3.0" ``` -------------------------------- TITLE: Install Laravel Cashier Paddle DESCRIPTION: Install the Cashier package for Paddle using the Composer package manager. SOURCE: https://laravel.com/docs/12.x/cashier-paddle LANGUAGE: bash CODE: ``` composer require laravel/cashier-paddle ``` -------------------------------- TITLE: Textarea Input - Laravel DESCRIPTION: Provides an example of using the textarea function to get multi-line input from the user. It prompts the user with a question and returns their input. SOURCE: https://laravel.com/docs/12.x/prompts LANGUAGE: php CODE: ``` use function Laravel\Prompts\textarea; $story = textarea('Tell me a story.'); ``` -------------------------------- TITLE: Install Flysystem Path Prefixing Driver DESCRIPTION: Installs the Flysystem path-prefixing package using Composer, which is required for creating scoped filesystems in Laravel. SOURCE: https://laravel.com/docs/12.x/filesystem LANGUAGE: bash CODE: ``` composer require league/flysystem-path-prefixing "^3.0" ``` -------------------------------- TITLE: Connect to Database CLI using Artisan DESCRIPTION: This demonstrates how to use Laravel's Artisan command-line tool to connect to your database's interactive shell. The `php artisan db` command initiates a connection to the default database. You can also specify a connection name, like `php artisan db mysql`, to connect to a non-default database configured in your application. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: shell CODE: ``` php artisan db ``` LANGUAGE: shell CODE: ``` php artisan db mysql ``` -------------------------------- TITLE: Initialize Homestead Configuration DESCRIPTION: Executes the initialization script to create the `Homestead.yaml` configuration file. This file manages all Homestead settings. SOURCE: https://laravel.com/docs/12.x/homestead LANGUAGE: bash CODE: ``` # macOS / Linux... bash init.sh # Windows... init.bat ``` -------------------------------- TITLE: Laravel PHPDoc Example with Native Types DESCRIPTION: Shows a simplified Laravel documentation block where `@param` and `@return` attributes are omitted when native type hints are used. This is applicable for methods with clear return types like `void` or other scalar/object types. SOURCE: https://laravel.com/docs/12.x/contributions LANGUAGE: php CODE: ``` /** * Execute the job. */ public function handle(AudioProcessor $processor): void { // } ``` LANGUAGE: php CODE: ``` /** * Execute the job. */ public function handle(AudioProcessor $processor): void { // } ``` -------------------------------- TITLE: Checkout Homestead Release Branch DESCRIPTION: Navigates to the Homestead directory and checks out the 'release' branch, which contains the latest stable version of Homestead. SOURCE: https://laravel.com/docs/12.x/homestead LANGUAGE: bash CODE: ``` cd ~/Homestead git checkout release ``` -------------------------------- TITLE: Map a GET Route to a Controller Method in Laravel DESCRIPTION: This example demonstrates how to map a GET route to a specific controller method. It uses a closure to instantiate and call the `index` method on the `UserController`. SOURCE: https://laravel.com/docs/12.x/routing LANGUAGE: php CODE: ``` use App\Http\Controllers\UserController; Route::get('/user', [UserController::class, 'index']); ``` -------------------------------- TITLE: Testing Cache Facade with PHPUnit DESCRIPTION: Demonstrates how to test a Laravel route utilizing the Cache facade with PHPUnit. This example mocks the 'get' method of the Cache facade and verifies the output in the response. SOURCE: https://laravel.com/docs/12.x/facades LANGUAGE: php CODE: ``` 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'); } ``` -------------------------------- TITLE: Testing Cache Facade with Pest DESCRIPTION: Provides an example of testing a Laravel route that uses the Cache facade with the Pest testing framework. It shows how to mock the Cache facade's 'get' method and assert the response. SOURCE: https://laravel.com/docs/12.x/facades LANGUAGE: php CODE: ``` use Illuminate\Support\Facades\Cache; test('basic example', function () { Cache::shouldReceive('get') ->with('key') ->andReturn('value'); $response = $this->get('/cache'); $response->assertSee('value'); }); ``` -------------------------------- TITLE: Install Dropbox Flysystem Adapter DESCRIPTION: Installs the community-maintained Flysystem adapter for Dropbox, enabling its use as a custom filesystem driver in Laravel. SOURCE: https://laravel.com/docs/12.x/filesystem LANGUAGE: bash CODE: ``` composer require spatie/flysystem-dropbox ``` -------------------------------- TITLE: Start Laravel Octane Server using Artisan DESCRIPTION: Demonstrates the Artisan command to start the Octane server. This command utilizes the server specified in the application's octane configuration file. SOURCE: https://laravel.com/docs/12.x/octane LANGUAGE: bash CODE: ``` php artisan octane:start ``` -------------------------------- TITLE: Update Homestead Dependencies (Composer) DESCRIPTION: Command to update Homestead dependencies when installed via Composer. Ensure the `laravel/homestead` package version is specified correctly in `composer.json`. SOURCE: https://laravel.com/docs/12.x/homestead LANGUAGE: bash CODE: ``` composer update ``` -------------------------------- TITLE: Testing Podcast Publishing with PHPUnit (PHP) DESCRIPTION: Provides an example of testing the Podcast model's publish functionality using PHPUnit. Similar to the Pest example, it leverages Laravel's facade testing utilities to mock the `Publisher` facade, allowing for isolated unit testing. SOURCE: https://laravel.com/docs/12.x/facades LANGUAGE: php CODE: ``` create(); Publisher::shouldReceive('publish')->once()->with($podcast); $podcast->publish(); } } ``` -------------------------------- TITLE: Start Tailing Logs with Pail DESCRIPTION: Initiates the Pail command to start tailing application logs. Press Ctrl+C to stop. SOURCE: https://laravel.com/docs/12.x/logging LANGUAGE: bash CODE: ``` php artisan pail ``` -------------------------------- TITLE: Monitor Long Database Queries in Laravel DESCRIPTION: This snippet shows how to monitor and react to database queries that exceed a specified time threshold during a single request. It uses the `whenQueryingForLongerThan` method from the `DB` facade, typically implemented in a service provider's `boot` method. This helps identify and address performance bottlenecks caused by slow database operations. SOURCE: https://laravel.com/docs/12.x/database LANGUAGE: php CODE: ``` withoutDefer(); } } ``` -------------------------------- TITLE: Install ReactPHP UV Extension DESCRIPTION: Install the `ext-uv` PHP extension using PECL to enable Reverb to use a more efficient event loop for handling a large number of concurrent WebSocket connections. SOURCE: https://laravel.com/docs/12.x/reverb LANGUAGE: bash CODE: ``` pecl install uv ``` -------------------------------- TITLE: Implicit Unique Rule Example in Laravel DESCRIPTION: Demonstrates how Laravel's 'unique' rule does not run on empty strings by default. This example shows a validation setup where an empty 'name' attribute passes the 'unique:users,name' rule. SOURCE: https://laravel.com/docs/12.x/validation LANGUAGE: php CODE: ``` use Illuminate\Support\Facades\Validator; $rules = ['name' => 'unique:users,name']; $input = ['name' => '']; Validator::make($input, $rules)->passes(); // true ``` -------------------------------- TITLE: Chipper CI Configuration for Laravel Dusk DESCRIPTION: This YAML configuration file sets up the environment and pipeline for running Laravel Dusk tests on Chipper CI. It includes environment settings for PHP and Node, service setup for Dusk, and defines pipeline steps for installing dependencies, compiling assets, and executing browser tests using PHP's built-in server. SOURCE: https://laravel.com/docs/dusk LANGUAGE: yaml CODE: ``` # 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 ``` -------------------------------- TITLE: Mocking Cache Facade Get Method with Pest DESCRIPTION: This example shows how to mock the `get` method of the `Cache` facade using Pest. It configures the mock to expect a specific argument and return a predefined value, then tests a route that interacts with the cache. SOURCE: https://laravel.com/docs/12.x/mocking LANGUAGE: php CODE: ``` with('key') ->andReturn('value'); $response = $this->get('/users'); // ... }); ``` -------------------------------- TITLE: Install vite-plugin-manifest-sri DESCRIPTION: Installs the necessary NPM plugin to enable Subresource Integrity (SRI) hashing for Vite-generated assets. SOURCE: https://laravel.com/docs/12.x/vite LANGUAGE: bash CODE: ``` npm install --save-dev vite-plugin-manifest-sri ``` -------------------------------- TITLE: Install PHP and Laravel Installer on Windows DESCRIPTION: Installs PHP 8.4, Composer, and the Laravel installer on Windows using PowerShell. It bypasses execution policy for the current process and downloads the installer script. Run PowerShell as administrator. SOURCE: https://laravel.com/docs/12 LANGUAGE: powershell CODE: ``` # 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')) ``` -------------------------------- TITLE: Install Laravel Fortify DESCRIPTION: Installs the Laravel Fortify package using the Composer package manager. This is the first step to integrate Fortify into a Laravel project. SOURCE: https://laravel.com/docs/12.x/fortify LANGUAGE: shell CODE: ``` composer require laravel/fortify ``` -------------------------------- TITLE: Install Laravel Telescope Locally DESCRIPTION: Installs Laravel Telescope as a development dependency using Composer and registers its service providers with Artisan commands. This is for local development environments only. SOURCE: https://laravel.com/docs/12.x/telescope LANGUAGE: shell CODE: ``` composer require laravel/telescope --dev php artisan telescope:install php artisan migrate ``` -------------------------------- TITLE: Install Octane and FrankenPHP with Laravel Sail DESCRIPTION: Commands to install Laravel Octane and set up FrankenPHP with Laravel Sail. This involves updating Sail, installing Octane via Composer, and then installing the FrankenPHP binary using an Artisan command. SOURCE: https://laravel.com/docs/octane LANGUAGE: bash CODE: ``` ./vendor/bin/sail up ./vendor/bin/sail composer require laravel/octane ``` LANGUAGE: bash CODE: ``` ./vendor/bin/sail artisan octane:install --server=frankenphp ``` -------------------------------- TITLE: Install Frontend Dependencies with NPM DESCRIPTION: Installs all frontend dependencies defined in the `package.json` file, including Vite and the Laravel plugin. This command is essential after setting up a new Laravel project or when updating dependencies. SOURCE: https://laravel.com/docs/12.x/vite LANGUAGE: bash CODE: ``` npm install ``` -------------------------------- TITLE: Install Laravel Sanctum for API DESCRIPTION: Installs Laravel Sanctum to provide a token authentication guard for API consumers. This command also creates the routes/api.php file. SOURCE: https://laravel.com/docs/12.x/routing LANGUAGE: APIDOC CODE: ``` ## Install Laravel Sanctum ### Description Installs Laravel Sanctum to provide a token authentication guard for API consumers. This command also creates the routes/api.php file. ### Method Artisan Command ### Endpoint N/A ### Parameters None ### Request Example ```bash php artisan install:api ``` ### Response N/A ``` -------------------------------- TITLE: Run Pint with Verbose Output DESCRIPTION: Execute Pint and display detailed information about the changes made to the files. The `-v` option provides more insight into Pint's operations. SOURCE: https://laravel.com/docs/12.x/pint LANGUAGE: bash CODE: ``` ./vendor/bin/pint -v ``` -------------------------------- TITLE: Get Process ID in Laravel DESCRIPTION: Retrieves the operating system assigned process ID (PID) of a running or started process using the `id` method. SOURCE: https://laravel.com/docs/12.x/processes LANGUAGE: PHP CODE: ``` $process = Process::start('bash import.sh'); return $process->id(); ``` -------------------------------- TITLE: Start Laravel Reverb Server DESCRIPTION: Starts the Reverb WebSocket server using the Artisan command. By default, it runs on 0.0.0.0:8080, accessible from all network interfaces. SOURCE: https://laravel.com/docs/12.x/reverb LANGUAGE: bash CODE: ``` php artisan reverb:start ``` -------------------------------- TITLE: Enforce Minimum Test Coverage Threshold (Shell) DESCRIPTION: Set a minimum acceptable test coverage percentage using the --min option. If the test suite's coverage falls below this threshold, the tests will fail, ensuring a baseline level of code coverage. SOURCE: https://laravel.com/docs/12.x/testing LANGUAGE: bash CODE: ``` php artisan test --coverage --min=80.3 ```