### Example Database Connection URL Format Source: https://github.com/laravel/docs/blob/12.x/database.md This snippet shows an example of a database connection URL, commonly provided by managed database services, which encapsulates all connection details in a single string. ```html mysql://root:password@127.0.0.1/forge?charset=UTF-8 ``` -------------------------------- ### Install Ably Broadcasting via Laravel Artisan Command Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md This Artisan command automates the setup process for Ably broadcasting. It installs necessary PHP and JavaScript SDKs, prompts for credentials, and updates your `.env` file, streamlining Ably integration. ```shell php artisan install:broadcasting --ably ``` -------------------------------- ### Install Ably PHP SDK for Laravel Broadcasting Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md This Composer command installs the `ably/ably-php` package, which is essential for integrating Ably as your broadcasting driver in Laravel. Run this command in your project's root directory for manual setup. ```shell composer require ably/ably-php ``` -------------------------------- ### Manually Install Laravel Reverb Composer Package Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Installs the Laravel Reverb package via Composer. This is a prerequisite for using Reverb as a broadcasting driver and is typically followed by 'php artisan reverb:install' to complete the setup. ```shell composer require laravel/reverb ``` -------------------------------- ### Install Frontend Dependencies and Start Laravel Development Server Source: https://github.com/laravel/docs/blob/12.x/starter-kits.md These commands navigate into the newly created Laravel project directory, install the necessary frontend dependencies using NPM, build the assets, and then start the Laravel development server. This makes the application accessible via a web browser. ```shell cd my-app npm install && npm run build composer run dev ``` -------------------------------- ### Create Laravel Eloquent Observer using Artisan Command Source: https://github.com/laravel/docs/blob/12.x/eloquent.md This Artisan command generates a new observer class for a specified Eloquent model. It places the file in the `app/Observers` directory and pre-populates it with common event methods, simplifying the initial setup of an observer. ```shell php artisan make:observer UserObserver --model=User ``` -------------------------------- ### Install and Configure Laravel Reverb Post-Composer Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Completes the installation of Laravel Reverb after the Composer package has been installed. This command publishes Reverb's configuration, adds required environment variables, and enables event broadcasting for the application. ```shell php artisan reverb:install ``` -------------------------------- ### Start Laravel Local Development Servers Source: https://github.com/laravel/docs/blob/12.x/installation.md These commands navigate into your new application directory, install frontend dependencies, build assets, and then start Laravel's local development server, queue worker, and Vite development server simultaneously. Your application will be accessible at http://localhost:8000. ```shell cd example-app npm install && npm run build composer run dev ``` -------------------------------- ### Install Paratest and Run Laravel Tests in Parallel (Shell) Source: https://github.com/laravel/docs/blob/12.x/testing.md To enable parallel testing in Laravel, first install the `brianium/paratest` Composer package as a development dependency. Once installed, execute the `test` Artisan command with the `--parallel` option to run your tests simultaneously across multiple processes, significantly reducing execution time. ```shell composer require brianium/paratest --dev php artisan test --parallel ``` -------------------------------- ### Return Channel Instance with Eloquent Model in PHP Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md This PHP example shows how to return a `Channel` instance directly, passing an Eloquent model to its constructor. Laravel will then automatically convert the model into a channel name string using its internal conventions. ```php return [new Channel($this->user)]; ``` -------------------------------- ### Install Laravel Event Broadcasting with Pusher Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Installs and configures Pusher Channels as the event broadcaster. This command prompts for Pusher credentials, installs the Pusher PHP and JavaScript SDKs, and updates the application's .env file with the necessary Pusher environment variables. ```shell php artisan install:broadcasting --pusher ``` -------------------------------- ### Running a Basic Select Query with Bindings in Laravel PHP Source: https://github.com/laravel/docs/blob/12.x/database.md This example demonstrates how to perform a basic `SELECT` query using the `DB` facade's `select` method within a Laravel controller. It shows selecting users with a `where` clause and parameterized bindings to prevent SQL injection, then returning the results to a view. ```php $users]); } } ``` -------------------------------- ### Install Laravel Valet Services Source: https://github.com/laravel/docs/blob/12.x/valet.md Executes the Valet `install` command to configure and set up Valet and DnsMasq. This command also configures necessary daemons to launch automatically when your system starts, ensuring Valet's services are always running. ```shell valet install ``` -------------------------------- ### Inspect Eloquent Model Details with Artisan Source: https://github.com/laravel/docs/blob/12.x/eloquent.md Utilize the `model:show` Artisan command to get a comprehensive overview of an Eloquent model's attributes and relationships directly from the command line, aiding in model inspection. ```shell php artisan model:show Flight ``` -------------------------------- ### Replicate Eloquent Model in Laravel Source: https://github.com/laravel/docs/blob/12.x/eloquent.md Demonstrates how to create an unsaved copy of an existing Eloquent model instance using the `replicate()` method. This is useful for instances sharing many attributes, allowing modification before saving. The example replicates a 'shipping' address to a 'billing' address. ```php 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(); ``` -------------------------------- ### Install Laravel Echo and Pusher JS NPM Packages Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Installs the `laravel-echo` and `pusher-js` packages as development dependencies. These packages are essential for enabling WebSocket communication in the frontend, as Reverb utilizes the Pusher protocol. ```shell npm install --save-dev laravel-echo pusher-js ``` -------------------------------- ### Configure Laravel Echo for Reverb Broadcasting in JavaScript, React, and Vue Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Initializes and configures the Laravel Echo instance to use the 'reverb' broadcaster. This setup involves importing Echo and Pusher, then defining the connection parameters like key, host, ports, and transport methods for different JavaScript frameworks. Note that React and Vue examples use `configureEcho` and comment out the environment variables, implying they are passed differently or are examples of available options. ```javascript 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'] }); ``` ```javascript 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'], }); ``` ```javascript 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'], }); ``` -------------------------------- ### Listen to public events using the useEchoPublic hook (React & Vue) Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Provides examples for implementing the `useEchoPublic` hook in both React and Vue components to effortlessly connect to and listen for events broadcast on public channels. ```js import { useEchoPublic } from "@laravel/echo-react"; useEchoPublic("posts", "PostPublished", (e) => { console.log(e.post); }); ``` ```vue ``` -------------------------------- ### Get Laravel Table Overview with db:table Source: https://github.com/laravel/docs/blob/12.x/database.md To get a detailed overview of an individual table, including its columns, types, attributes, keys, and indexes, use the `db:table` Artisan command followed by the table name. ```shell php artisan db:table users ``` -------------------------------- ### Install Laravel Event Broadcasting with Reverb Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Installs and configures Laravel Reverb as the event broadcaster. This command adds required Composer and NPM packages, and updates the application's .env file with Reverb-specific environment variables for real-time event handling. ```shell php artisan install:broadcasting --reverb ``` -------------------------------- ### Run Laravel Dusk Installation Artisan Command Source: https://github.com/laravel/docs/blob/12.x/dusk.md Executes the `dusk:install` Artisan command to set up the Dusk environment. This command creates the `tests/Browser` directory, an example Dusk test, and installs the Chrome Driver binary for your operating system. ```shell php artisan dusk:install ``` -------------------------------- ### Configure Laravel Echo with an Existing Pusher Client Instance Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Demonstrates how to integrate an already configured Pusher Channels client instance with Laravel Echo. This approach allows developers to leverage custom or pre-initialized Pusher client configurations while still utilizing Echo's streamlined broadcasting capabilities, avoiding redundant client setup. ```js 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) }); ``` -------------------------------- ### Define Basic Laravel Test (Pest & PHPUnit) Source: https://github.com/laravel/docs/blob/12.x/testing.md Examples demonstrating how to define a simple, basic test case using both Pest and PHPUnit frameworks within a Laravel application. These tests assert a true condition and are typically found in the `tests/Unit` or `tests/Feature` directories. ```php toBeTrue(); }); ``` ```php assertTrue(true); } } ``` -------------------------------- ### Executing Select Queries with Named Bindings in Laravel PHP Source: https://github.com/laravel/docs/blob/12.x/database.md Instead of using positional `?` placeholders, Laravel allows queries to use named bindings. This example demonstrates a `select` query where parameters are identified by names, making the query more readable and self-documenting. ```php $results = DB::select('select * from users where id = :id', ['id' => 1]); ``` -------------------------------- ### Install Pusher PHP SDK for Laravel Broadcasting Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md This Composer command installs the official Pusher Channels PHP SDK, which is a required dependency for enabling Pusher as your broadcasting driver in Laravel. Execute it in your project's root directory. ```shell composer require pusher/pusher-php-server ``` -------------------------------- ### Start Homestead Virtual Machine Source: https://github.com/laravel/docs/blob/12.x/homestead.md This command boots up the Homestead virtual machine, configuring shared folders and Nginx sites as defined in your `Homestead.yaml`. It should be run from your Homestead directory to initiate the development environment. ```shell vagrant up ``` -------------------------------- ### Iterate Over an Eloquent Collection (PHP) Source: https://github.com/laravel/docs/blob/12.x/eloquent.md This example shows how an `Illuminate\Database\Eloquent\Collection` can be iterated over using a `foreach` loop, similar to a standard PHP array. It accesses the `name` property of each `Flight` model within the collection. ```php foreach ($flights as $flight) { echo $flight->name; } ``` -------------------------------- ### Handling No Results with Eloquent findOr/firstOr in PHP Source: https://github.com/laravel/docs/blob/12.x/eloquent.md This example shows how to handle cases where no model is found using Eloquent's `findOr` and `firstOr` methods. These methods execute a provided closure if no records match the query, allowing custom fallback logic or default values. ```php $flight = Flight::findOr(1, function () { // ... }); $flight = Flight::where('legs', '>', 3)->firstOr(function () { // ... }); ``` -------------------------------- ### Standard Database URL Schema Convention Source: https://github.com/laravel/docs/blob/12.x/database.md This snippet illustrates the general schema convention for database connection URLs, detailing the components like driver, credentials, host, port, database name, and additional options. ```html driver://username:password@host:port/database?options ``` -------------------------------- ### Demonstrating Implicit Commits in Laravel Unprepared Statements PHP Source: https://github.com/laravel/docs/blob/12.x/database.md This example shows a scenario where `DB::unprepared` can lead to implicit commits, especially when creating tables within transactions. Such operations can unexpectedly commit the entire transaction, making Laravel unaware of the database's transaction state. ```php DB::unprepared('create table a (col varchar(1) null)'); ``` -------------------------------- ### Update Laravel Installer via Composer Global Source: https://github.com/laravel/docs/blob/12.x/upgrade.md This command updates the `laravel/installer` package globally using Composer, ensuring compatibility with Laravel 12.x and new starter kits. Run this if you installed the Laravel installer via `composer global require` to get the latest version. ```shell composer global update laravel/installer ``` -------------------------------- ### Report Code Coverage for Laravel Tests (Shell) Source: https://github.com/laravel/docs/blob/12.x/testing.md To assess how thoroughly your application's code is exercised by your test suite, use the `--coverage` option with the `test` Artisan command. This feature requires a code coverage driver like Xdebug or PCOV to be installed and enabled on your system. ```shell php artisan test --coverage ``` -------------------------------- ### Install PHP, Composer, and Laravel Installer on macOS Source: https://github.com/laravel/docs/blob/12.x/installation.md This command initiates the installation of PHP, Composer, and the Laravel installer on macOS systems. It utilizes a bash script to streamline the setup of essential development tools required for Laravel application development. ```shell /bin/bash -c "$(curl -fsSL https://php.new/install/mac/8.4)" ``` -------------------------------- ### Compile Frontend Assets with NPM Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Executes the npm build command to compile the application's frontend assets. This step ensures that all JavaScript changes, including the Laravel Echo configuration, are processed and ready for deployment. ```shell npm run build ``` -------------------------------- ### Start Asynchronous Processes in Laravel Source: https://github.com/laravel/docs/blob/12.x/processes.md This example shows how to start a process asynchronously using the `start` method, allowing the application to continue performing other tasks while the process runs in the background. It also demonstrates polling the process status with `running()` and waiting for completion with `wait()`. ```php $process = Process::timeout(120)->start('bash import.sh'); while ($process->running()) { // ... } $result = $process->wait(); ``` -------------------------------- ### Manually Begin a Database Transaction in Laravel Source: https://github.com/laravel/docs/blob/12.x/database.md Explains how to manually initiate a database transaction using `DB::beginTransaction()`, providing fine-grained control over when to commit or rollback database changes. ```php use Illuminate\Support\Facades\DB; DB::beginTransaction(); ``` -------------------------------- ### Initialize Laravel Event Broadcasting Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Initializes Laravel's event broadcasting system. This command creates necessary configuration files (config/broadcasting.php, routes/channels.php) and prompts the user to select a broadcasting service, enabling the framework's real-time event capabilities. ```shell php artisan install:broadcasting ``` -------------------------------- ### GitHub Actions Workflow for Laravel Dusk Tests Source: https://github.com/laravel/docs/blob/12.x/dusk.md This GitHub Actions workflow provides a starting point for running Laravel Dusk tests. It defines steps for environment preparation, database creation, dependency installation, key generation, Chrome driver setup, and running both the Chrome driver and the Laravel server in the background before executing Dusk tests. It also includes steps to upload screenshots and console logs on test failure. ```yaml 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 ``` -------------------------------- ### Update an existing Eloquent model in PHP Source: https://github.com/laravel/docs/blob/12.x/eloquent.md This example demonstrates how to update an existing Eloquent model. First, retrieve the model, modify its attributes, and then call the `save()` method. The `updated_at` timestamp is automatically managed by Eloquent, so manual setting is not required. ```php use App\Models\Flight; $flight = Flight::find(1); $flight->name = 'Paris to London'; $flight->save(); ``` -------------------------------- ### Install Laravel Passport with API Support Source: https://github.com/laravel/docs/blob/12.x/passport.md Run this Artisan command to install Laravel Passport. It publishes and executes necessary database migrations for OAuth2 clients and access tokens, and generates the encryption keys required for secure access tokens. ```shell php artisan install:api --passport ``` -------------------------------- ### Inspect Laravel Database Overview with db:show Source: https://github.com/laravel/docs/blob/12.x/database.md The `db:show` Artisan command provides an overview of your database, including its size, type, open connections, and a summary of tables. You can specify a database connection and include table row counts or view details with `--database`, `--counts`, and `--views` options. ```shell php artisan db:show ``` ```shell php artisan db:show --database=pgsql ``` ```shell php artisan db:show --counts --views ``` -------------------------------- ### Write Custom Global Scope Class in Laravel Source: https://github.com/laravel/docs/blob/12.x/eloquent.md Provides an example of implementing a custom global scope by creating a class that implements `Illuminate\Database\Eloquent\Scope`. The `apply` method is where query constraints are added, such as a `where` clause to filter by `created_at`. ```php where('created_at', '<', now()->subYears(2000)); } } ``` -------------------------------- ### Query Subscriptions by Status Using Laravel Cashier Scopes Source: https://github.com/laravel/docs/blob/12.x/billing.md This PHP example demonstrates how to use Cashier's query scopes to retrieve subscriptions based on their status. It shows how to get all active subscriptions or all canceled subscriptions for a specific user. ```php // Get all active subscriptions... $subscriptions = Subscription::query()->active()->get(); // Get all of the canceled subscriptions for a user... $subscriptions = $user->subscriptions()->canceled()->get(); ``` -------------------------------- ### Create Laravel Application with Community Starter Kit Source: https://github.com/laravel/docs/blob/12.x/starter-kits.md This command initializes a new Laravel application, `my-app`, leveraging a community-maintained starter kit hosted on Packagist. The `--using` flag specifies the desired starter kit, streamlining the project setup with predefined configurations and features. ```shell laravel new my-app --using=example/starter-kit ``` -------------------------------- ### Connect to Laravel Database CLI Source: https://github.com/laravel/docs/blob/12.x/database.md Use the `db` Artisan command to connect to your database's command-line interface. You can optionally specify a database connection name to connect to a non-default connection. ```shell php artisan db ``` ```shell php artisan db mysql ``` -------------------------------- ### Run Laravel Tests with Artisan Arguments Source: https://github.com/laravel/docs/blob/12.x/testing.md Command to execute Laravel tests using the Artisan test runner, demonstrating how to pass additional arguments like specifying a test suite or stopping on the first failure. This allows for more granular control over test execution and debugging. ```shell php artisan test --testsuite=Feature --stop-on-failure ``` -------------------------------- ### Schedule Model Prune Artisan Command in Laravel Source: https://github.com/laravel/docs/blob/12.x/eloquent.md Demonstrates how to schedule the `model:prune` Artisan command using Laravel's task scheduler. This command automatically detects and prunes models marked with the `Prunable` trait, with the example showing daily execution. ```php use Illuminate\Support\Facades\Schedule; Schedule::command('model:prune')->daily(); ``` -------------------------------- ### Understand Livewire Project File Structure Source: https://github.com/laravel/docs/blob/12.x/starter-kits.md Outlines the typical directory structure for a Livewire-based Laravel starter kit, specifically highlighting where reusable components, Flux components, Livewire pages, partials, and main application views are located within the `resources/views` directory. This provides insight into the frontend code organization. ```text 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 ``` -------------------------------- ### Selecting Multiple Result Sets from Stored Procedures in Laravel PHP Source: https://github.com/laravel/docs/blob/12.x/database.md For applications calling stored procedures that return multiple result sets, the `DB::selectResultSets` method can retrieve all of them. This example demonstrates calling a stored procedure and receiving multiple arrays of results. ```php [$options, $notifications] = DB::selectResultSets( "CALL get_user_options_and_notifications(?)", $request->user()->id ); ``` -------------------------------- ### Install Laravel Homestead as Project Dependency Source: https://github.com/laravel/docs/blob/12.x/homestead.md Use this Composer command to install Laravel Homestead as a development dependency for a specific project. This approach allows for a dedicated, version-controlled Homestead instance per project, making it ideal for sharing project setups. ```shell composer require laravel/homestead --dev ``` -------------------------------- ### Publish shadcn UI Components for React and Vue Source: https://github.com/laravel/docs/blob/12.x/starter-kits.md These commands demonstrate how to publish specific `shadcn/ui` (for React) or `shadcn-vue` (for Vue) components using `npx`. Running these commands downloads and integrates the specified UI component into your project's frontend directory, making it available for use in your application. Ensure `npx` is available in your development environment. ```shell npx shadcn@latest add switch ``` ```shell npx shadcn-vue@latest add switch ``` -------------------------------- ### Clone Homestead Repository via Git Source: https://github.com/laravel/docs/blob/12.x/homestead.md This command clones the Laravel Homestead repository from GitHub into a 'Homestead' folder within the user's home directory. This is the first step to installing Homestead on your host machine. ```shell git clone https://github.com/laravel/homestead.git ~/Homestead ``` -------------------------------- ### Restore soft-deleted related Laravel Eloquent models Source: https://github.com/laravel/docs/blob/12.x/eloquent.md This example shows how to restore soft-deleted models that are related to another model. The `restore()` method is called on the relationship query, targeting the related models for restoration. ```php $flight->history()->restore(); ``` -------------------------------- ### List Laravel Broadcast Channel Authorization Callbacks Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Use the Artisan command `php artisan channel:list` to view a comprehensive list of all registered broadcast authorization callbacks within your Laravel application, aiding in debugging and overview. ```shell php artisan channel:list ``` -------------------------------- ### Start Laravel Reverb Server Source: https://github.com/laravel/docs/blob/12.x/reverb.md This command initializes the Laravel Reverb WebSocket server using Artisan, by default binding to `0.0.0.0:8080`. It's the basic way to get the server running without custom configurations. ```shell php artisan reverb:start ``` -------------------------------- ### Create New Laravel Application with Starter Kit Source: https://github.com/laravel/docs/blob/12.x/starter-kits.md After installing the Laravel CLI, this command is used to create a new Laravel application. The CLI will then prompt the user to select their desired starter kit, such as React, Vue, or Livewire. ```shell laravel new my-app ``` -------------------------------- ### GET /oauth/authorize Source: https://github.com/laravel/docs/blob/12.x/passport.md This endpoint displays the authorization view to the user, prompting them to approve or deny a client's request for authorization. It's the initial step in the Authorization Code Grant flow. ```APIDOC ## GET /oauth/authorize ### Description This endpoint is used to display the authorization view to a user. The user is redirected here by a client application to grant or deny access to their resources. Passport will automatically define this route after you configure the authorization view. ### Method GET ### Endpoint /oauth/authorize ### Parameters #### Query Parameters - **response_type** (string) - Required - Specifies the desired response type (e.g., `code`). - **client_id** (string) - Required - The client application's public identifier. - **redirect_uri** (string) - Required - The URI to which the user will be redirected after authorization. - **scope** (string) - Optional - A space-delimited list of scopes the client is requesting. - **state** (string) - Recommended - An opaque value used by the client to maintain state between the request and callback. ### Request Example GET /oauth/authorize?response_type=code&client_id=1&redirect_uri=https://example.com/callback&scope=view-profile&state=random_string ### Response #### Success Response (200) - **HTML View** - The rendered HTML view prompting the user for authorization approval or denial. #### Response Example ```html
``` ``` -------------------------------- ### Stream Eloquent Records with Lazy Collection (PHP) Source: https://github.com/laravel/docs/blob/12.x/eloquent.md This example utilizes the `lazy` method to retrieve Eloquent models as a `LazyCollection`, allowing them to be processed as a single stream while internally fetching data in chunks. This approach is memory-efficient for very large datasets, providing an iterable `Flight` model at a time. ```php use App\Models\Flight; foreach (Flight::lazy() as $flight) { // ... } ``` -------------------------------- ### Access Specific Database Connection in Laravel Source: https://github.com/laravel/docs/blob/12.x/database.md Demonstrates how to access a specific database connection defined in your `config/database.php` file using the `DB::connection()` method to perform database operations on that particular connection. ```php use Illuminate\Support\Facades\DB; $users = DB::connection('sqlite')->select(/* ... */); ``` -------------------------------- ### Simulate Authenticated User with Scopes in Laravel Passport Tests Source: https://github.com/laravel/docs/blob/12.x/passport.md This snippet demonstrates how to simulate an authenticated user with specific scopes in Laravel Passport tests. It utilizes the `Passport::actingAs` method, which accepts a user instance and an array of desired scopes. This setup enables testing of routes that require user authentication and scope validation, ensuring the API responds with the expected HTTP status code. Examples are provided for both Pest and PHPUnit testing frameworks. ```php use App\Models\User; use Laravel\Passport\Passport; test('orders can be created', function () { Passport::actingAs( User::factory()->create(), ['orders:create'] ); $response = $this->post('/api/orders'); $response->assertStatus(201); }); ``` ```php use App\Models\User; use Laravel\Passport\Passport; public function test_orders_can_be_created(): void { Passport::actingAs( User::factory()->create(), ['orders:create'] ); $response = $this->post('/api/orders'); $response->assertStatus(201); } ``` -------------------------------- ### Create Laravel Test File Source: https://github.com/laravel/docs/blob/12.x/testing.md Commands to generate new test files for Laravel applications, distinguishing between feature and unit tests. Feature tests are placed in `tests/Feature` by default, while unit tests are placed in `tests/Unit` using the `--unit` option. ```shell php artisan make:test UserTest ``` ```shell php artisan make:test UserTest --unit ``` -------------------------------- ### Configure Pusher Channels Credentials in Laravel .env Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Set these environment variables in your application's `.env` file to provide the necessary credentials for Laravel to connect to Pusher. Replace the placeholder values with your actual Pusher application ID, key, secret, and cluster. ```ini 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" ``` -------------------------------- ### Define Single Private Channel for Laravel Event Broadcasts Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md The `broadcastOn` method defines which channels an event uses. For secure, user-specific updates, a `PrivateChannel` is returned. This example links the channel to an `order.id`, ensuring only authorized users can receive updates. ```php use IlluminateBroadcastingChannel; use IlluminateBroadcastingPrivateChannel; /** * Get the channel the event should broadcast on. */ public function broadcastOn(): Channel { return new PrivateChannel('orders.'.$this->order->id); } ``` -------------------------------- ### Start a Pool of Concurrent Laravel Processes Source: https://github.com/laravel/docs/blob/12.x/processes.md This PHP example shows how to define and start a pool of multiple concurrent asynchronous processes using Laravel's `Process::pool` method. It defines three commands within the pool's closure and then `start`s them, optionally providing a callback for real-time output from any process in the pool. The `running()` method can then be used to monitor the active processes. ```php 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(); ``` -------------------------------- ### Permanently delete soft-deleted related Laravel Eloquent models Source: https://github.com/laravel/docs/blob/12.x/eloquent.md This example illustrates how to permanently delete soft-deleted models that are related to another model. The `forceDelete()` method is called on the relationship query to physically remove the related records. ```php $flight->history()->forceDelete(); ``` -------------------------------- ### Insert New Eloquent Model Record Using `save` Method in Laravel Controller Source: https://github.com/laravel/docs/blob/12.x/eloquent.md Demonstrates how to insert a new record into the database by instantiating an Eloquent model, setting its attributes, and calling the `save()` method. This example is presented within a Laravel controller's `store` method, showing how to handle form submissions and persist data. Timestamps (`created_at`, `updated_at`) are automatically managed. ```php name = $request->name; $flight->save(); return redirect('/flights'); } } ``` -------------------------------- ### Example Laravel Model Broadcast Event Payload in JSON Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md This JSON object illustrates the typical payload structure for a Laravel model broadcast event. It includes the `model` object with its properties (like `id` and `title`) and a `socket` identifier, representing the data sent to client-side applications. ```json { "model": { "id": 1, "title": "My first post" ... }, ... "socket": "someSocketId" } ``` -------------------------------- ### GET /passport/device/authorizations/authorize Source: https://github.com/laravel/docs/blob/12.x/passport.md This endpoint is used by the end-user on a secondary device (e.g., computer, smartphone) to enter the 'user code' provided by the browserless device. It initiates the authorization process by displaying a page for user input. ```APIDOC ## GET /passport/device/authorizations/authorize ### Description This endpoint is used by the end-user on a secondary device (e.g., computer, smartphone) to enter the 'user code' provided by the browserless device. It initiates the authorization process by displaying a page for user input. ### Method GET ### Endpoint /passport/device/authorizations/authorize ### Parameters #### Path Parameters - No path parameters. #### Query Parameters - **user_code** (string) - Required - The unique user code provided to the user by the device initiating the authorization flow. This code links the user's browser session to the device's request. #### Request Body - No request body. ### Request Example GET /passport/device/authorizations/authorize?user_code=ABCD-EFGH ### Response #### Success Response (200) - Returns an HTML page (as configured via `Passport::deviceUserCodeView()`) that prompts the user to confirm the authorization or displays an error if the user code is invalid/expired. #### Response Example (HTML page content for user code entry or authorization approval) ``` -------------------------------- ### Retrieve Eloquent Model or Throw Exception in PHP Source: https://github.com/laravel/docs/blob/12.x/eloquent.md Demonstrates how to use `findOrFail` and `firstOrFail` methods on an Eloquent model. These methods retrieve a record based on given criteria or throw an `Illuminate\Database\Eloquent\ModelNotFoundException` if no record is found. This is useful for robust error handling, especially in routes or controllers. ```php $flight = Flight::findOrFail(1); $flight = Flight::where('legs', '>', 3)->firstOrFail(); ``` -------------------------------- ### Leave a channel and its associated private/presence channels with Laravel Echo (JavaScript) Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Shows how to use the `leave` method to disconnect from a channel, including any private or presence channels linked to it, in a single operation. ```js Echo.leave(`orders.${this.order.id}`); ``` -------------------------------- ### Configure Laravel Echo Instance for Pusher in JavaScript, React, and Vue Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Initializes the Laravel Echo instance to use Pusher for broadcasting. This configuration sets up the broadcaster, API key, cluster, and forces TLS, allowing the frontend to subscribe to real-time events from the Laravel backend. Examples are provided for plain JavaScript, React, and Vue. ```js 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 }); ``` ```js 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"], }); ``` ```js 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 Inertia SSR Server via Artisan Command Source: https://github.com/laravel/docs/blob/12.x/vite.md For applications using SSR with Inertia, you can leverage the `php artisan inertia:start-ssr` command to efficiently start the server-side rendering server. This command integrates with Laravel's ecosystem for a streamlined SSR setup. ```shell php artisan inertia:start-ssr ``` -------------------------------- ### Listen for Private Channel Events with Laravel Echo in JavaScript Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md This example illustrates how to listen for events on a private channel using Laravel Echo in JavaScript. The `private` method is used instead of `channel` for authentication-protected channels. Multiple `listen` calls can be chained to handle various events on the same private channel. ```javascript Echo.private(`orders.${this.order.id}`) .listen(/* ... */) .listen(/* ... */) .listen(/* ... */); ``` -------------------------------- ### Retrieve Underlying PDO Instance in Laravel Source: https://github.com/laravel/docs/blob/12.x/database.md Illustrates how to obtain the raw, underlying PDO instance from a database connection using the `getPdo` method on a connection instance, allowing for direct interaction with the PDO object. ```php $pdo = DB::connection()->getPdo(); ``` -------------------------------- ### GET /oauth/authorize Source: https://github.com/laravel/docs/blob/12.x/passport.md Initiates the OAuth 2.0 Authorization Code Grant flow. The consuming application redirects the user's browser to this URL to request authorization. Upon successful approval, an authorization code will be returned to the specified redirect_uri. ```APIDOC ## GET /oauth/authorize ### Description This endpoint initiates the OAuth 2.0 Authorization Code Grant flow. The consuming application redirects the user's browser to this URL to request authorization. Upon successful approval, an authorization code will be returned to the redirect_uri. ### Method GET ### Endpoint /oauth/authorize ### Parameters #### Query Parameters - **client_id** (string) - Required - The client ID obtained when the OAuth client was created. - **redirect_uri** (string) - Required - The URL to which the user will be redirected after authorization. Must match the 'redirect' URL registered with the client. - **response_type** (string) - Required - Must be 'code' for the authorization code grant flow. - **scope** (string) - Optional - A space-separated list of scopes the consuming application is requesting (e.g., 'user:read orders:create'). - **state** (string) - Optional - An opaque value used to maintain state between the request and the callback. Used for CSRF protection. - **prompt** (string) - Optional - Specifies authentication behavior. Can be 'none', 'consent', or 'login'. - 'none': Throws an authentication error if the user is not authenticated. - 'consent': Always displays the authorization approval screen. - 'login': Always prompts the user to re-login. ### Request Example ``` GET https://passport-app.test/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_string_here&prompt=none ``` ### Response #### Success Response (302 Found - Redirect) - **code** (string) - The authorization code, returned as a query parameter in the redirect_uri. - **state** (string) - The same 'state' value that was sent in the request, returned as a query parameter in the redirect_uri. #### Response Example ``` HTTP/1.1 302 Found Location: https://third-party-app.com/callback?code=AUTH_CODE_HERE&state=random_string_here ``` ``` -------------------------------- ### Install Minio Object Storage Feature in Homestead Source: https://github.com/laravel/docs/blob/12.x/homestead.md To install the Minio object storage server feature, add `minio: true` to the `features` section of your `Homestead.yaml` file. Minio provides an S3-compatible API for local object storage. ```yaml minio: true ``` -------------------------------- ### Executing Unprepared Database Statements in Laravel PHP Source: https://github.com/laravel/docs/blob/12.x/database.md The `DB::unprepared` method allows executing SQL statements without parameter binding. This is useful for specific scenarios but carries a significant risk of SQL injection if user-controlled input is included. Use with extreme caution. ```php DB::unprepared('update users set votes = 100 where name = "Dries"'); ``` -------------------------------- ### Create Stripe Setup Intent in PHP for Subscriptions Source: https://github.com/laravel/docs/blob/12.x/billing.md This PHP snippet demonstrates how to use Laravel Cashier's `createSetupIntent` method on a Billable user to generate a Stripe Setup Intent. This intent is then passed to a view, typically for rendering a form to collect customer payment details for future subscription usage. ```php return view('update-payment-method', [ 'intent' => $user->createSetupIntent() ]); ``` -------------------------------- ### Connect to Presence Channel using useEchoPresence Hook (React/Vue) Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md This snippet demonstrates how to connect to a Laravel Echo presence channel using the `useEchoPresence` hook. It provides examples for both React and Vue applications, showing how to subscribe to a specific event (e.g., 'PostPublished') on a given channel (e.g., 'posts') and log the event data upon reception. ```js import { useEchoPresence } from "@laravel/echo-react"; useEchoPresence("posts", "PostPublished", (e) => { console.log(e.post); }); ``` ```vue ``` -------------------------------- ### Listen for Laravel Broadcast Events with Echo (React & Vue) Source: https://github.com/laravel/docs/blob/12.x/broadcasting.md Client-side applications use Laravel Echo to listen for broadcast events. The `useEcho` hook simplifies subscribing to channels and handling events. This example shows listening to `orders.${orderId}` for `OrderShipmentStatusUpdated` events in both React and Vue. ```javascript import { useEcho } from "@laravel/echo-react"; useEcho( `orders.${orderId}`, "OrderShipmentStatusUpdated", (e) => { console.log(e.order); }, ); ``` ```vue ```