### Example Database URL Source: https://laravel.com/docs/12.x/database An example of a database URL string, typically provided by managed database providers like AWS or Heroku. ```html mysql://root:password@127.0.0.1/forge?charset=UTF-8 ``` -------------------------------- ### Basic Pest Test Example Source: https://laravel.com/docs/12.x/testing An example of a basic test using the Pest testing framework. ```php toBeTrue(); }); ``` -------------------------------- ### Basic PHPUnit Test Example Source: https://laravel.com/docs/12.x/testing An example of a basic test using the PHPUnit testing framework. ```php assertTrue(true); } } ``` -------------------------------- ### Using firstOrCreate and firstOrNew Source: https://laravel.com/docs/12.x/eloquent Examples of retrieving a model or creating/instantiating it if it doesn't exist, with and without additional attributes. ```php 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'] ); ``` -------------------------------- ### Install Paratest and Run Tests in Parallel Source: https://laravel.com/docs/12.x/testing Install the `brianium/paratest` Composer package and run tests simultaneously across multiple processes using the `--parallel` option. ```shell composer require brianium/paratest --dev php artisan test --parallel ``` -------------------------------- ### Running an Insert Statement Source: https://laravel.com/docs/12.x/database Example of executing an `INSERT` statement using the `DB::insert` method with parameter bindings. ```php use Illuminate\Support\Facades\DB; DB::insert('insert into users (id, name) values (?, ?)', [1, 'Marc']); ``` -------------------------------- ### Using Named Bindings Source: https://laravel.com/docs/12.x/database Example of executing a query using named parameter bindings instead of positional `?` placeholders. ```php $results = DB::select('select * from users where id = :id', ['id' => 1]); ``` -------------------------------- ### Using Aggregate Methods Source: https://laravel.com/docs/12.x/eloquent Examples of using count and max aggregate methods with Eloquent models. ```php $count = Flight::where('active', 1)->count(); $max = Flight::where('active', 1)->max('price'); ``` -------------------------------- ### Running a Select Query Source: https://laravel.com/docs/12.x/database Example of a basic SELECT query using the `DB::select` method with parameter binding to retrieve active users. ```php $users]); } } ``` -------------------------------- ### Install frontend dependencies and start development server Source: https://laravel.com/docs/12.x/starter-kits After creating your Laravel application, navigate into the directory, install its frontend dependencies via NPM, and start the Laravel development server. ```shell cd my-app npm install && npm run build composer run dev ``` -------------------------------- ### Configuring Read and Write Database Connections Source: https://laravel.com/docs/12.x/database Example configuration for a MySQL connection demonstrating how to specify separate hosts for read and write operations, including the 'sticky' option. ```php 'mysql' => [ 'driver' => 'mysql', 'read' => [ 'host' => [ '192.168.1.1', '196.168.1.2', ], ], 'write' => [ 'host' => [ '192.168.1.3', ], ], 'sticky' => true, 'port' => env('DB_PORT', '3306'), '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([ (PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'), ]) : [], ], ``` -------------------------------- ### Connect to Database CLI Source: https://laravel.com/docs/12.x/database Connects to the default database CLI or a specified connection. ```shell php artisan db ``` ```shell php artisan db mysql ``` -------------------------------- ### Utilizing Dynamic Scopes Source: https://laravel.com/docs/12.x/eloquent Example of calling a dynamic scope with a parameter. ```php $users = User::ofType('admin')->get(); ``` -------------------------------- ### Running an Unprepared Statement Source: https://laravel.com/docs/12.x/database Example of executing an SQL statement without binding any values using the `DB::unprepared` method. ```php DB::unprepared('update users set votes = 100 where name = "Dries"'); ``` -------------------------------- ### SQLite Database Connection Source: https://laravel.com/docs/12.x/database Configuring environment variables to point to an SQLite database. ```ini DB_CONNECTION=sqlite DB_DATABASE=/absolute/path/to/database.sqlite ``` -------------------------------- ### Running a General Statement Source: https://laravel.com/docs/12.x/database Example of executing a general database statement that does not return any value using the `DB::statement` method. ```php DB::statement('drop table users'); ``` -------------------------------- ### Listen for DatabaseBusy Event Source: https://laravel.com/docs/12.x/database Example of listening for the `DatabaseBusy` event in `AppServiceProvider` to send a notification when the database approaches max connections. ```php 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 )); }); } ``` -------------------------------- ### Building Queries with Constraints Source: https://laravel.com/docs/12.x/eloquent Example of adding additional constraints to an Eloquent query using query builder methods before retrieving results with `get`. ```php $flights = Flight::where('active', 1) ->orderBy('name') ->limit(10) ->get(); ``` -------------------------------- ### Comparing Two Models Source: https://laravel.com/docs/12.x/eloquent Examples of using the `is` and `isNot` methods to compare two Eloquent models. ```php if ($post->is($anotherPost)) { // ... } if ($post->isNot($anotherPost)) { // ... } ``` -------------------------------- ### Start Laravel local development server Source: https://laravel.com/docs/12.x Navigate into the application directory, install frontend dependencies, build assets, and then start Laravel's local development server, queue worker, and Vite development server. ```bash 1cd example-app 2npm install && npm run build 3composer run dev ``` -------------------------------- ### Create a Unit Test Source: https://laravel.com/docs/12.x/testing Command to generate a new test case in the 'tests/Unit' directory. ```shell php artisan make:test UserTest --unit ``` -------------------------------- ### Start Laravel Development Server Source: https://laravel.com/docs/12.x/installation Commands to navigate into the application directory, install npm dependencies, build frontend assets, and start Laravel's local development server, queue worker, and Vite development server. ```shell cd example-app npm install && npm run build composer run dev ``` -------------------------------- ### MySQL Database Configuration Source: https://laravel.com/docs/12.x/installation Example of updating the .env file to use MySQL as the database driver. ```ini DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD= ``` -------------------------------- ### Iterating with `cursor` Source: https://laravel.com/docs/12.x/eloquent Example of using the `cursor` method to iterate over Eloquent models, reducing memory consumption. ```php use App\Models\Flight; foreach (Flight::where('destination', 'Zurich')->cursor() as $flight) { // ... } ``` -------------------------------- ### Retrieving Single Models Source: https://laravel.com/docs/12.x/eloquent Examples of using `find`, `first`, and `firstWhere` to retrieve single Eloquent model instances. ```php 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); ``` -------------------------------- ### Parallel Testing Hooks Source: https://laravel.com/docs/12.x/testing Define code to be executed on `setUp` and `tearDown` of a process or test case, including `setUpTestDatabase`. ```php withAttributes([ 'hidden' => true, ], asConditions: false); ``` -------------------------------- ### Manually beginning a database transaction Source: https://laravel.com/docs/12.x/database Start a database transaction manually, providing complete control over commit and rollback. ```php use Illuminate\Support\Facades\DB; DB::beginTransaction(); ``` -------------------------------- ### Manually Registering an Observer in AppServiceProvider Source: https://laravel.com/docs/12.x/eloquent Example of registering an observer in the `boot` method of `AppServiceProvider`. ```php use App\Models\User; use App\Observers\UserObserver; /** * Bootstrap any application services. */ public function boot(): void { User::observe(UserObserver::class); } ``` -------------------------------- ### Running an Update Statement Source: https://laravel.com/docs/12.x/database Example of executing an `UPDATE` statement using the `DB::update` method, which returns the number of affected rows. ```php use Illuminate\Support\Facades\DB; $affected = DB::update( 'update users set votes = 100 where name = ?', ['Anita'] ); ``` -------------------------------- ### Inspect a model Source: https://laravel.com/docs/12.x/eloquent Use the `model:show` Artisan command to get an overview of a model's attributes and relations. ```shell php artisan model:show Flight ``` -------------------------------- ### Defining Dynamic Scopes Source: https://laravel.com/docs/12.x/eloquent Example of defining a dynamic scope `ofType` that accepts a parameter. ```php where('type', $type); } } ``` -------------------------------- ### Create New Application with Community Starter Kit Source: https://laravel.com/docs/12.x/starter-kits Use the Laravel installer with the `--using` flag to create a new application with a community-maintained starter kit. ```shell laravel new my-app --using=example/starter-kit ``` -------------------------------- ### Utilizing Local Scopes Source: https://laravel.com/docs/12.x/eloquent Example of chaining multiple local scopes and an `orderBy` clause. ```php use App\Models\User; $users = User::popular()->active()->orderBy('created_at')->get(); ``` -------------------------------- ### Run Tests with Pest Source: https://laravel.com/docs/12.x/testing Command to execute tests using the Pest runner. ```shell ./vendor/bin/pest ``` -------------------------------- ### Creating Models with Pending Attributes Source: https://laravel.com/docs/12.x/eloquent Example of creating a model using a scope defined with `withAttributes`. ```php $draft = Post::draft()->create(['title' => 'In Progress']); $draft->hidden; // true ``` -------------------------------- ### Writing Global Scopes Source: https://laravel.com/docs/12.x/eloquent Example of a class implementing the Illuminate\Database\Eloquent\Scope interface to define a global scope. ```php where('created_at', '<', now()->minus(years: 2000)); } } ``` -------------------------------- ### Generate model with migration Source: https://laravel.com/docs/12.x/eloquent Generate a new model and its corresponding database migration file. ```shell php artisan make:model Flight --migration ``` -------------------------------- ### Create a Feature Test Source: https://laravel.com/docs/12.x/testing Command to generate a new test case in the 'tests/Feature' directory. ```shell php artisan make:test UserTest ``` -------------------------------- ### Example Production Log Stack Configuration Source: https://laravel.com/docs/12.x/logging An example configuration demonstrating how to build a log stack combining 'syslog' and 'slack' channels, including their individual configurations. ```php 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['syslog', 'slack'], // [tl! add] 'ignore_exceptions' => false, ], 'syslog' => [ 'driver' => 'syslog', 'level' => env('LOG_LEVEL', 'debug'), 'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER), 'replace_placeholders' => true, ], 'slack' => [ 'driver' => 'slack', 'url' => env('LOG_SLACK_WEBHOOK_URL'), 'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'), 'emoji' => env('LOG_SLACK_EMOJI', ':boom:'), 'level' => env('LOG_LEVEL', 'critical'), 'replace_placeholders' => true, ], ], ``` -------------------------------- ### Performing Other Operations Quietly Source: https://laravel.com/docs/12.x/eloquent Examples of deleting, force deleting, and restoring models without dispatching events. ```php $user->deleteQuietly(); $user->forceDeleteQuietly(); $user->restoreQuietly(); ``` -------------------------------- ### Install Dusk Package Source: https://laravel.com/docs/12.x/dusk Artisan command to set up Dusk, create the browser test directory, an example test, and install the ChromeDriver binary. ```shell php artisan dusk:install ``` -------------------------------- ### Comparing Related Models Source: https://laravel.com/docs/12.x/eloquent Example of using the `is` method to compare a related model without issuing a query. ```php if ($post->author()->is($user)) { // ... } ``` -------------------------------- ### `get()` method example Source: https://laravel.com/docs/12.x/collections Returns the item at a given key, or `null` if the key does not exist. ```php $collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']); $value = $collection->get('name'); // Taylor ``` -------------------------------- ### Removing Multiple Global Scopes Source: https://laravel.com/docs/12.x/eloquent Examples of removing all, specific, or all except specific global scopes from a query. ```php // Remove all of the global scopes... User::withoutGlobalScopes()->get(); // Remove some of the global scopes... User::withoutGlobalScopes([ FirstScope::class, SecondScope::class ])->get(); // Remove all global scopes except the given ones... User::withoutGlobalScopesExcept([ SecondScope::class, ])->get(); ``` -------------------------------- ### Subquery Selects Source: https://laravel.com/docs/12.x/eloquent Example of using `addSelect` with a subquery to retrieve the name of the most recently arrived flight for each destination. ```php 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(); ``` -------------------------------- ### Listening for all executed queries Source: https://laravel.com/docs/12.x/database Register a closure in a service provider's `boot` method to be invoked for every SQL query executed, useful for logging or debugging. ```php sql; // $query->bindings; // $query->time; // $query->toRawSql(); }); } } ``` -------------------------------- ### Creating a Carbon instance with `Illuminate\Support\Carbon` Source: https://laravel.com/docs/12.x/helpers Example of creating a new `Carbon` instance using the `Illuminate\Support\Carbon` class. ```php use Illuminate\Support\Carbon; $now = Carbon::now(); ``` -------------------------------- ### Retrieving All Records Source: https://laravel.com/docs/12.x/eloquent Example of retrieving all records from a model's associated database table using the `all` method. ```php use App\Models\Flight; foreach (Flight::all() as $flight) { echo $flight->name; } ``` -------------------------------- ### prepend Method Example Source: https://laravel.com/docs/12.x/strings Example demonstrating how to use the `prepend` method to add values to the beginning of a string. ```php use Illuminate\Support\Str; $string = Str::of('Framework')->prepend('Laravel '); // Laravel Framework ``` -------------------------------- ### Vue Frontend Directory Structure Source: https://laravel.com/docs/12.x/starter-kits Overview of the `resources/js` directory structure in the Vue starter kit. ```text resources/js/ ├── components/ # Reusable Vue components ├── composables/ # Vue composables / hooks ├── layouts/ # Application layouts ├── lib/ # Utility functions and configuration ├── pages/ # Page components └── types/ # TypeScript definitions ``` -------------------------------- ### Generated User Observer Class Source: https://laravel.com/docs/12.x/eloquent Example of a newly generated observer class with methods for common Eloquent events. ```php */ protected $guarded = []; ``` -------------------------------- ### Mass Assigning JSON Columns Source: https://laravel.com/docs/12.x/eloquent Example of specifying a JSON column key in the $fillable array for mass assignment. ```php /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'options->enabled', ]; ``` -------------------------------- ### Inspect Database Overview Source: https://laravel.com/docs/12.x/database Shows an overview of the database, including size, type, connections, and table summary. Options for specifying connection, row counts, and view details are available. ```shell php artisan db:show ``` ```shell php artisan db:show --database=pgsql ``` ```shell php artisan db:show --counts --views ``` -------------------------------- ### Using a Published shadcn-vue Component Source: https://laravel.com/docs/12.x/starter-kits Example of importing and using the `Switch` component in a Vue page after publishing. ```vue ``` -------------------------------- ### Subquery Ordering Source: https://laravel.com/docs/12.x/eloquent Example of using `orderByDesc` with a subquery to sort destinations based on the arrival time of their last flight. ```php return Destination::orderByDesc( Flight::select('arrived_at') ->whereColumn('destination_id', 'destinations.id') ->orderByDesc('arrived_at') ->limit(1) )->get(); ``` -------------------------------- ### Defining Default Attribute Values Source: https://laravel.com/docs/12.x/eloquent Example of defining default values for model attributes using the `$attributes` property. ```php '[]', 'delayed' => false, ]; } ``` -------------------------------- ### Inserting a New Model Instance Source: https://laravel.com/docs/12.x/eloquent Demonstrates how to create a new Eloquent model instance, set its attributes, and save it to the database. ```php name = $request->name; $flight->save(); return redirect('/flights'); } } ``` -------------------------------- ### padBoth Method Examples Source: https://laravel.com/docs/12.x/strings Examples demonstrating how to use the `padBoth` method to pad both sides of a string. ```php use Illuminate\Support\Str; $padded = Str::of('James')->padBoth(10, '_'); // '__James___' $padded = Str::of('James')->padBoth(10); // ' James ' ``` -------------------------------- ### Publishing shadcn/ui Components for React Source: https://laravel.com/docs/12.x/starter-kits Command to publish a shadcn/ui component, such as 'switch', into the React starter kit's frontend. ```shell npx shadcn@latest add switch ``` -------------------------------- ### Using WithCachedConfig Trait with PHPUnit Source: https://laravel.com/docs/12.x/testing Example demonstrating how to apply the WithCachedConfig trait in a PHPUnit test class to cache configuration. ```php use(WithCachedConfig::class); // ... ``` -------------------------------- ### Switching to Header Layout Source: https://laravel.com/docs/12.x/starter-kits Example of modifying `resources/views/layouts/app.blade.php` to use the header layout with Flux UI. ```blade {{ $slot }} ``` -------------------------------- ### Defining Scope with Pending Attributes Source: https://laravel.com/docs/12.x/eloquent Example of defining a `draft` scope that uses `withAttributes` to add attributes to created models. ```php withAttributes([ 'hidden' => true, ]); } } ``` -------------------------------- ### Defining Local Scopes Source: https://laravel.com/docs/12.x/eloquent Example of defining 'popular' and 'active' local scopes on a User model using the `#[Scope]` attribute. ```php where('votes', '>', 100); } /** * Scope a query to only include active users. */ #[Scope] protected function active(Builder $query): void { $query->where('active', 1); } } ``` -------------------------------- ### Run Boost Installer Source: https://laravel.com/docs/12.x/ai Execute the interactive installer after Boost has been installed. ```shell php artisan boost:install ``` -------------------------------- ### Creating URI Instances Source: https://laravel.com/docs/12.x/helpers Demonstrates various ways to create a Uri instance, including from a string, paths, named routes, signed routes, temporary signed routes, controller actions, and the current request URL. ```php 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()->plus(minutes: 5)); $uri = Uri::action([UserController::class, 'index']); $uri = Uri::action(InvokableController::class); // Generate a URI instance from the current request URL... $uri = $request->uri(); ``` -------------------------------- ### Anonymous Global Scopes Source: https://laravel.com/docs/12.x/eloquent Example of defining a global scope using a closure within the model's booted method. ```php where('created_at', '<', now()->minus(years: 2000)); }); } } ``` -------------------------------- ### Using ULID Keys Source: https://laravel.com/docs/12.x/eloquent Example of using the HasUlids trait to automatically generate ULIDs for a model's primary key. ```php 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" ``` -------------------------------- ### Registering Package Views Source: https://laravel.com/docs/12.x/packages Example of using `loadViewsFrom` in a service provider's `boot` method to register package views. ```php /** * Bootstrap any package services. */ public function boot(): void { $this->loadViewsFrom(__DIR__.'/../resources/views', 'courier'); } ``` -------------------------------- ### Inspect Individual Table Overview Source: https://laravel.com/docs/12.x/database Provides a general overview of a database table, including its columns, types, attributes, keys, and indexes. ```shell php artisan db:table users ``` -------------------------------- ### Using UUID Keys Source: https://laravel.com/docs/12.x/eloquent Example of using the HasUuids trait to automatically generate UUIDs for a model's primary key. ```php 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; // "018f2b5c-6a7f-7b12-9d6f-2f8a4e0c9c11" ``` -------------------------------- ### Basic Browser Test Example (PHPUnit) Source: https://laravel.com/docs/12.x/dusk Demonstrates how to create a browser instance and perform basic login actions using PHPUnit. ```php 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'); }); } } ``` -------------------------------- ### Basic Eloquent Model Class Source: https://laravel.com/docs/12.x/eloquent An example of a basic Eloquent model class, typically located in `app/Models` and extending `Illuminate\Database\Eloquent\Model`. ```php strlen($value) > 0 ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() : [], hint: 'The user will receive an email immediately.' ); ``` -------------------------------- ### Example Third-Party Package AI Guidelines File Source: https://laravel.com/docs/12.x/boost An example of the `resources/boost/guidelines/core.blade.php` file content, demonstrating the structure for AI guidelines, including how to embed a code snippet within the guidelines using `@verbatim` and ``. ```php ## Package Name This package provides [brief description of functionality]. ### Features - Feature 1: [clear & short description]. - Feature 2: [clear & short description]. Example usage: @verbatim $result = PackageName::featureTwo($param1, $param2); @endverbatim ``` -------------------------------- ### Autocomplete with Placeholder, Default, and Hint Source: https://laravel.com/docs/12.x/prompts Example of using `autocomplete` with `placeholder`, `default`, and `hint` arguments. ```php $name = autocomplete( label: 'What is your name?', options: ['Taylor', 'Dayle', 'Jess', 'Nuno', 'Tim'], placeholder: 'E.g. Taylor', default: $user?->name, hint: 'Use tab to accept, up/down to cycle.' ); ``` -------------------------------- ### Combining Scopes with Higher-Order `orWhere` Source: https://laravel.com/docs/12.x/eloquent Example of fluently chaining scopes together using Laravel's higher-order `orWhere` method. ```php $users = User::popular()->orWhere->active()->get(); ``` -------------------------------- ### Create a new Laravel application Source: https://laravel.com/docs/12.x Use the Laravel installer to create a new application. The installer will prompt you to select your preferred testing framework, database, and starter kit. ```bash 1laravel new example-app laravel new example-app ``` -------------------------------- ### Applying Global Scopes in booted method Source: https://laravel.com/docs/12.x/eloquent Example of manually registering a global scope by overriding the model's booted method. ```php minus(months: 1)); } } ``` -------------------------------- ### Benchmarking with multiple iterations Source: https://laravel.com/docs/12.x/helpers Demonstrates how to specify the number of iterations for a benchmark to get an average execution time. ```php Benchmark::dd(fn () => User::count(), iterations: 10); // 0.5 ms ``` -------------------------------- ### Implementing the Prunable Trait Source: https://laravel.com/docs/12.x/eloquent Example of a Flight model using the Prunable trait and defining the prunable method to specify which models should be deleted. ```php minus(months: 1)); } } ``` -------------------------------- ### Accessing the underlying PDO instance Source: https://laravel.com/docs/12.x/database Retrieve the raw PDO instance from a database connection for direct interaction. ```php $pdo = DB::connection()->getPdo(); ``` -------------------------------- ### Retrieving Single Models with Fallback Source: https://laravel.com/docs/12.x/eloquent Examples of using `findOr` and `firstOr` to retrieve a single model or execute a closure if no results are found. ```php $flight = Flight::findOr(1, function () { // ... }); $flight = Flight::where('legs', '>', 3)->firstOr(function () { // ... }); ``` -------------------------------- ### Start Laravel and Inertia SSR Servers Source: https://laravel.com/docs/12.x/starter-kits Command to start the Laravel development server and Inertia SSR server after building an SSR compatible bundle. ```shell composer dev:ssr ``` -------------------------------- ### Refreshing a Model Instance (refresh) Source: https://laravel.com/docs/12.x/eloquent Example of re-hydrating an existing model instance with fresh data from the database using the `refresh` method. ```php $flight = Flight::where('number', 'FR 900')->first(); $flight->number = 'FR 456'; $flight->refresh(); $flight->number; // "FR 900" ``` -------------------------------- ### Basic Pipeline Usage with Closures Source: https://laravel.com/docs/12.x/helpers Demonstrates how to use the Pipeline facade to send an input through a series of closures, where each closure can inspect or modify the input. ```php use Closure; use App\Models\User; use Illuminate\Support\Facades\Pipeline; $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); ``` -------------------------------- ### Refreshing a Model Instance (fresh) Source: https://laravel.com/docs/12.x/eloquent Example of re-retrieving a model from the database without affecting the existing instance using the `fresh` method. ```php $flight = Flight::where('number', 'FR 900')->first(); $freshFlight = $flight->fresh(); ``` -------------------------------- ### Using a Published shadcn/ui Switch Component in React Source: https://laravel.com/docs/12.x/starter-kits Example of importing and using the 'Switch' component from shadcn/ui within a React page component after it has been published. ```jsx import { Switch } from "@/components/ui/switch" const MyPage = () => { return (
); }; export default MyPage; ``` -------------------------------- ### Displaying Secondary Information with `suggest` Source: https://laravel.com/docs/12.x/prompts Example demonstrating how to use the `info` argument with the `suggest` function to display additional information based on the currently highlighted option. ```php $name = suggest( label: 'What is your name?', options: ['Taylor', 'Dayle'], info: fn (string $value) => match ($value) { 'Taylor' => 'Administrator', 'Dayle' => 'Contributor', default => null, } ); ``` -------------------------------- ### Selecting Multiple Result Sets Source: https://laravel.com/docs/12.x/database Example of retrieving multiple result sets from a stored procedure using the `DB::selectResultSets` method. ```php [$options, $notifications] = DB::selectResultSets( "CALL get_user_options_and_notifications(?)", $request->user()->id ); ``` -------------------------------- ### Basic Browser Test Example (Pest) Source: https://laravel.com/docs/12.x/dusk Demonstrates how to create a browser instance and perform basic login actions using Pest. ```php 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'); }); }); ``` -------------------------------- ### Selecting Scalar Values Source: https://laravel.com/docs/12.x/database Example of retrieving a single scalar value directly from a database query using the `DB::scalar` method. ```php $burgers = DB::scalar( "select count(case when food = 'burger' then 1 end) as burgers from menu" ); ``` -------------------------------- ### Building and Starting SSR Server Source: https://laravel.com/docs/12.x/vite Commands to build the assets and start the SSR server. ```shell npm run build node bootstrap/ssr/ssr.js ``` -------------------------------- ### Restrict Routes with Verified Middleware Source: https://laravel.com/docs/12.x/starter-kits Add the `verified` middleware to routes to restrict access until the user's email address is verified. ```php Route::middleware(['auth', 'verified'])->group(function () { Route::get('dashboard', function () { return Inertia::render('dashboard'); })->name('dashboard'); }); ``` -------------------------------- ### Iterating Select Query Results Source: https://laravel.com/docs/12.x/database Example demonstrating how to iterate over the results returned by `DB::select`, where each result is a PHP `stdClass` object. ```php use Illuminate\Support\Facades\DB; $users = DB::select('select * from users'); foreach ($users as $user) { echo $user->name; } ``` -------------------------------- ### Chunking using Lazy Collections Source: https://laravel.com/docs/12.x/eloquent Example of using the `lazy` method to process records in chunks, returning a flattened `LazyCollection` for stream-like interaction. ```php use App\Models\Flight; foreach (Flight::lazy() as $flight) { // ... } ``` -------------------------------- ### Installation Source: https://laravel.com/docs/12.x/prompts Install Laravel Prompts using Composer. ```shell composer require laravel/prompts ``` -------------------------------- ### Suggest with Placeholder, Default, and Hint Source: https://laravel.com/docs/12.x/prompts Illustrates how to include placeholder text, a default value, and an informational hint with the `suggest` function. ```php $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.' ); ``` -------------------------------- ### Enabling and Disabling Features Source: https://laravel.com/docs/12.x/starter-kits Configuration for enabling or disabling Fortify features in `config/fortify.php`. ```php use Laravel\Fortify\Features; 'features' => [ Features::registration(), Features::resetPasswords(), Features::emailVerification(), Features::twoFactorAuthentication([ 'confirm' => true, 'confirmPassword' => true, ]), ], ```