### Installing Laravel Installer Globally Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/installation.md This command installs the Laravel installer globally on your system using Composer. Once installed, it provides a convenient `laravel new` command for creating new projects, streamlining the setup process. ```Shell composer global require laravel/installer ``` -------------------------------- ### Starting Laravel's Local Development Server Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/installation.md These commands navigate into the newly created Laravel project directory and then start the built-in Artisan development server. This makes the application accessible in a web browser, typically at `http://localhost:8000`, for local development and testing. ```Shell cd example-app php artisan serve ``` -------------------------------- ### Setting Up and Running Parallel Tests in Laravel Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md These commands show how to install the necessary Composer package for parallel testing and then execute your tests simultaneously across multiple processes to significantly reduce execution time. ```shell composer require brianium/paratest --dev php artisan test --parallel ``` -------------------------------- ### Starting Laravel Sail Docker Containers Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/installation.md After creating the Laravel project, navigate into its directory and execute this command to start the Docker containers for the application. This brings up the web server, database, and other services required for the Laravel application to run, applicable across macOS, Windows (WSL2), and Linux. ```shell cd example-app ./vendor/bin/sail up ``` -------------------------------- ### Creating a New Laravel Project with Laravel Installer Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/installation.md After globally installing the Laravel installer, this command creates a new Laravel project named 'example-app'. It offers a more concise and user-friendly alternative to Composer's `create-project` command for scaffolding new applications. ```Shell laravel new example-app ``` -------------------------------- ### Building Eloquent Queries with Chained Methods Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Build complex database queries using Eloquent's fluent query builder methods. This example demonstrates chaining `where`, `orderBy`, and `take` methods to filter, sort, and limit results before retrieving them with `get()`, returning an Eloquent collection. ```PHP $flights = Flight::where('active', 1) ->orderBy('name') ->take(10) ->get(); ``` -------------------------------- ### Creating a New Laravel Project with Sail Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/installation.md This command uses `curl` to download and execute a Laravel installation script, creating a new Laravel application named 'example-app' within the current directory. This is the initial step for setting up a Laravel project with Sail on macOS, Windows (WSL2), or Linux. ```shell curl -s "https://laravel.build/example-app" | bash ``` -------------------------------- ### Example SQL Query with Applied Global Scope Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This SQL snippet illustrates the resulting query when a global scope, such as `AncientScope`, is applied to an Eloquent model. It shows how the scope's `where` clause is integrated into the final database query. ```SQL select * from `users` where `created_at` < 0021-02-18 00:00:00 ``` -------------------------------- ### Basic PHPUnit Test Example in Laravel Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md This PHP code snippet illustrates a fundamental PHPUnit test class structure, demonstrating a simple assertion within a test method. This is a typical example found in `tests/Unit/ExampleTest.php`. ```php assertTrue(true); } } ``` -------------------------------- ### Running Laravel Tests with PHPUnit Executable Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md This command executes all tests in your Laravel application directly using the PHPUnit executable located in the `vendor/bin` directory. ```shell ./vendor/bin/phpunit ``` -------------------------------- ### Running Laravel Tests with Artisan Command Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md This command runs all tests in your Laravel application using the Artisan test runner, which provides verbose and developer-friendly reports. ```shell php artisan test ``` -------------------------------- ### Replicating Eloquent Models in Laravel PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This example demonstrates how to create an unsaved copy of an existing model instance using the `replicate` method. It's useful for creating new models that share most attributes with an existing one, allowing for quick modification and saving. ```PHP use AppModelsAddress; $shipping = Address::create([ 'type' => 'shipping', 'line_1' => '123 Example Street', 'city' => 'Victorville', 'state' => 'CA', 'postcode' => '90001', ]); $billing = $shipping->replicate()->fill([ 'type' => 'billing' ]); $billing->save(); ``` -------------------------------- ### Creating Pest PHP Test Cases in Laravel Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md These commands demonstrate how to generate test files compatible with Pest PHP, allowing you to create either feature or unit tests using the `--pest` option. ```shell php artisan make:test UserTest --pest php artisan make:test UserTest --unit --pest ``` -------------------------------- ### Handling Not Found Exceptions in Routes - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Provides an example of using `findOrFail` within a Laravel route closure. If the flight with the given ID is not found, a `ModelNotFoundException` is thrown, automatically resulting in a 404 HTTP response. ```PHP use App\Models\Flight; Route::get('/api/flights/{id}', function (string $id) { return Flight::findOrFail($id); }); ``` -------------------------------- ### Retrieving Single Eloquent Models or Fail - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Illustrates `findOrFail` and `firstOrFail` methods, which retrieve a single model or throw an `Illuminate\Database\Eloquent\ModelNotFoundException` if no result is found, useful for routes and controllers. ```PHP $flight = Flight::findOrFail(1); $flight = Flight::where('legs', '>', 3)->firstOrFail(); ``` -------------------------------- ### Running Specific Laravel Test Suites with Artisan Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md This command demonstrates how to pass specific PHPUnit arguments, such as `--testsuite` to run only feature tests and `--stop-on-failure` to halt execution on the first failure, to the Artisan `test` command. ```shell php artisan test --testsuite=Feature --stop-on-failure ``` -------------------------------- ### Configuring and Installing Valet Services - Shell Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/valet.md This command finalizes the Valet installation by configuring Nginx and DnsMasq. It sets up the necessary daemons to launch automatically when the system starts, enabling Valet to proxy requests to local sites on the `*.test` domain. ```Shell valet install ``` -------------------------------- ### Retrieving or Creating Models with `firstOrCreate` (Basic) - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Demonstrates how to use the `firstOrCreate` method to find a `Flight` model by name or create it if it doesn't exist. This method automatically persists the model to the database if created. ```PHP use App\Models\Flight; // Retrieve flight by name or create it if it doesn't exist... $flight = Flight::firstOrCreate([ 'name' => 'London to Paris' ]); ``` -------------------------------- ### Creating a Unit Test Case in Laravel Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md Use this command with the `--unit` option to generate a new test class specifically for unit tests, which focus on isolated portions of your code and do not boot the full Laravel application. ```shell php artisan make:test UserTest --unit ``` -------------------------------- ### Creating a New Laravel Project via Composer Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/installation.md This command initializes a new Laravel project named 'example-app' using Composer's `create-project` command, specifically targeting Laravel version 10.0. It's the standard and recommended way to scaffold a new Laravel application. ```Shell composer create-project "laravel/laravel:^10.0" example-app ``` -------------------------------- ### Running Reverb Installation Command Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/broadcasting.md After installing the Reverb package, this Artisan command publishes its configuration, updates broadcasting settings, and adds necessary environment variables. It automates the setup process for Reverb. ```sh php artisan reverb:install ``` -------------------------------- ### Creating Laravel Project with Sail and Devcontainer Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/installation.md This command extends the project creation process to include a default Devcontainer configuration. By adding the `devcontainer` parameter to the URL, Sail will set up the necessary files for development within a containerized environment. ```shell curl -s "https://laravel.build/example-app?with=mysql,redis&devcontainer" | bash ``` -------------------------------- ### Retrieving or Instantiating Models with `firstOrNew` (Basic) - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Shows how `firstOrNew` attempts to locate a `Flight` model by name. If not found, it returns a new `Flight` instance without persisting it to the database, requiring a manual `save` call. ```PHP use App\Models\Flight; // Retrieve flight by name or instantiate a new Flight instance... $flight = Flight::firstOrNew([ 'name' => 'London to Paris' ]); ``` -------------------------------- ### Creating Laravel Project with Specific Sail Services Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/installation.md This command allows you to specify which services (e.g., MySQL, Redis) should be included in your new Laravel application's `docker-compose.yml` file during project creation. The `with` query string parameter is used to list desired services. ```shell curl -s "https://laravel.build/example-app?with=mysql,redis" | bash ``` -------------------------------- ### Retrieving or Instantiating Models with `firstOrNew` (Extended) - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Demonstrates `firstOrNew` to find a `Flight` model or instantiate a new one with specified attributes. The new instance is not saved to the database, requiring explicit `save()` for persistence. ```PHP use App\Models\Flight; // 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'] ); ``` -------------------------------- ### Recreating Test Databases for Parallel Testing in Laravel Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md Use this command with the `--recreate-databases` option to force Laravel to drop and recreate test databases for each parallel process, ensuring a clean and isolated database state for every test run. ```shell php artisan test --parallel --recreate-databases ``` -------------------------------- ### Retrieving or Creating Models with `firstOrCreate` (Extended) - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Illustrates using `firstOrCreate` to find a `Flight` model by name, or create it with additional attributes (`delayed`, `arrival_time`) if not found. The second array argument provides attributes for creation. ```PHP use App\Models\Flight; // 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'] ); ``` -------------------------------- ### Creating a Feature Test Case in Laravel Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md This command generates a new test class within the `tests/Feature` directory, which is suitable for feature tests that interact with larger portions of your application, including HTTP requests. ```shell php artisan make:test UserTest ``` -------------------------------- ### Utilizing Dynamic Eloquent Scopes in PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This PHP example demonstrates how to call a dynamic local scope, `ofType`, passing the required argument 'admin'. This retrieves users whose 'type' attribute matches 'admin', showcasing how to apply parameterized query constraints. ```PHP $users = User::ofType('admin')->get(); ``` -------------------------------- ### Generating Test Coverage Report in Laravel Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md This command generates a test coverage report for your Laravel application, indicating how much of your application code is exercised by your tests. This feature requires Xdebug or PCOV. ```shell php artisan test --coverage ``` -------------------------------- ### Defining Parallel Testing Hooks in Laravel Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md This PHP code demonstrates how to use the `ParallelTesting` facade within a service provider to define custom hooks that execute at different stages of parallel test processes or test cases, such as setting up or tearing down resources. ```php name = $request->name; $flight->save(); return redirect('/flights'); } } ``` -------------------------------- ### Setting up Laravel Sail and Octane for FrankenPHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/octane.md Starts Laravel Sail and installs the Laravel Octane package via Composer within the Sail environment, preparing for FrankenPHP integration. ```Shell ./vendor/bin/sail up ./vendor/bin/sail composer require laravel/octane ``` -------------------------------- ### Running Parallel Tests with Custom Process Count in Laravel Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md This command allows you to explicitly define the number of parallel processes for test execution using the `--processes` option, overriding the default behavior of using available CPU cores. ```shell php artisan test --parallel --processes=4 ``` -------------------------------- ### Retrieving Single Eloquent Models with Fallback - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Demonstrates `findOr` and `firstOr` methods, which retrieve a single model or execute a given closure if no model is found. The return value of the closure becomes the result of the method. ```PHP $flight = Flight::findOr(1, function () { // ... }); $flight = Flight::where('legs', '>', 3)->firstOr(function () { // ... }); ``` -------------------------------- ### Running Laravel Breeze Installation for Livewire/API Stacks Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/starter-kits.md Initiates the `breeze:install` Artisan command, allowing selection of the Livewire or API frontend stack. After scaffolding, only database migrations are required, as these stacks typically do not involve separate frontend asset compilation via npm. ```shell php artisan breeze:install php artisan migrate ``` -------------------------------- ### Iterating Over Eloquent Collection - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Shows how to loop over an Eloquent collection using a `foreach` loop, treating it like a standard PHP array, since collections implement PHP's iterable interfaces. ```PHP foreach ($flights as $flight) { echo $flight->name; } ``` -------------------------------- ### Switching Docker Context to Default on Linux Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/installation.md This command is specifically for Linux users who are using Docker Desktop. It ensures that the Docker CLI is interacting with the default Docker context, which is necessary before creating a new Laravel project with Sail. ```shell docker context use default ``` -------------------------------- ### Populating Model Attributes with `fill` Method - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Demonstrates the `fill` method, which populates an existing model instance with an array of attributes. This method respects the `$fillable` or `$guarded` properties for mass assignment protection. ```PHP $flight->fill(['name' => 'Amsterdam to Frankfurt']); ``` -------------------------------- ### Using Password Prompt with Options in Laravel Prompts Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/prompts.md This example shows how to use the `password` function with additional options like `label`, `placeholder`, and an informational `hint` to guide the user. ```php $password = password( label: 'What is your password?', placeholder: 'password', hint: 'Minimum 8 characters.' ); ``` -------------------------------- ### Preparing Model for Pruning in Laravel PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This method is called before a prunable model is deleted. It's useful for performing cleanup tasks, such as deleting associated files or resources, before the model is permanently removed from the database. ```PHP /** * Prepare the model for pruning. */ protected function pruning(): void { // ... } ``` -------------------------------- ### Running Laravel Database Migrations Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/installation.md This Artisan command executes all pending database migrations for the Laravel application. It creates or updates the necessary database tables based on the migration files defined in the `database/migrations` directory, ensuring the database schema matches the application's requirements. ```Shell php artisan migrate ``` -------------------------------- ### Running Laravel Breeze Installation for Blade/Inertia Stacks Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/starter-kits.md Executes the `breeze:install` Artisan command to publish authentication views and resources, prompting for frontend stack selection (e.g., Blade, Vue, React). Subsequent commands run database migrations, install Node.js dependencies, and compile frontend assets for these stacks. ```shell php artisan breeze:install php artisan migrate npm install npm run dev ``` -------------------------------- ### Rejecting Models from Eloquent Collection - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Demonstrates how to use the `reject` method on an Eloquent collection to filter out models based on a given closure. In this example, flights marked as 'cancelled' are removed from the collection. ```PHP $flights = Flight::where('destination', 'Paris')->get(); $flights = $flights->reject(function (Flight $flight) { return $flight->cancelled; }); ``` -------------------------------- ### Enforcing Minimum Test Coverage Threshold in Laravel Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/testing.md This command allows you to define a minimum test coverage percentage using the `--min` option. If the actual coverage falls below this threshold, the test suite will fail, ensuring code quality standards are met. ```shell php artisan test --coverage --min=80.3 ``` -------------------------------- ### PHPDoc Example for Binding in PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/contributions.md This PHPDoc block demonstrates the standard documentation format for a PHP method in Laravel, including `@param` attributes for arguments, their types, and variable names, and `@throws` for exceptions. It shows the full syntax for documenting a method that registers a binding with a container. ```PHP /** * 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) { // ... } ``` -------------------------------- ### Mass Assignment with `create` Method - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Reiterates the use of the `create` method for mass assignment. This method allows creating a new model instance and populating its attributes from an array in a single step, requiring `$fillable` or `$guarded` protection. ```PHP use App\Models\Flight; $flight = Flight::create([ 'name' => 'London to Paris', ]); ``` -------------------------------- ### Removing All Global Scopes from Query in Laravel PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This example illustrates how to remove all global scopes applied to a query. Calling the `withoutGlobalScopes` method without any arguments will disable all previously registered global scopes for that specific query. ```PHP // Remove all of the global scopes... User::withoutGlobalScopes()->get(); ``` -------------------------------- ### Iterating with Eloquent Cursor - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Demonstrates the `cursor` method for highly memory-efficient iteration over large result sets. It executes a single query and hydrates models one by one as they are iterated, keeping only one model in memory at a time. ```PHP use App\Models\Flight; foreach (Flight::where('destination', 'Zurich')->cursor() as $flight) { // ... } ``` -------------------------------- ### Retrieving All Records with Eloquent `all()` Method Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Retrieve all records from a model's associated database table using the static `all()` method. This method returns an Eloquent collection, which can then be iterated over to access individual model instances and their attributes. ```PHP use App\Models\Flight; foreach (Flight::all() as $flight) { echo $flight->name; } ``` -------------------------------- ### Deleting Laravel Models by Multiple Primary Keys Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This example illustrates how to delete multiple Laravel Eloquent models by providing a variadic list of primary keys to the static `destroy` method. Each model corresponding to a provided key will be deleted. ```PHP Flight::destroy(1, 2, 3); ``` -------------------------------- ### Installing Laravel Breeze Composer Package Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/starter-kits.md This command installs the Laravel Breeze package as a development dependency using Composer. It's the initial step required before running the Artisan commands to scaffold the authentication system. ```shell composer require laravel/breeze --dev ``` -------------------------------- ### Building and Starting Vite SSR Server Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/vite.md These shell commands demonstrate the process of building Vite assets (including SSR) and then starting the Node.js SSR server. `npm run build` compiles the assets, and `node bootstrap/ssr/ssr.js` executes the server-side rendered application, making it available for requests. ```sh npm run build node bootstrap/ssr/ssr.js ``` -------------------------------- ### Restoring Soft Deleted Related Laravel Models Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This example illustrates how to restore soft deleted models that are related to another model. By chaining `restore()` on a relationship query, all soft deleted related models will have their `deleted_at` column set to `null`. ```PHP $flight->history()->restore(); ``` -------------------------------- ### Comparing Related Eloquent Models with `is` in PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This PHP example illustrates using the `is` method to compare a related Eloquent model without explicitly loading it. It checks if the `author` relationship of a `$post` model refers to the same user as `$user`, which is useful for efficient relationship comparisons. ```PHP if ($post->author()->is($user)) { // ... } ``` -------------------------------- ### Applying Global Scope in Model's Booted Method in Laravel PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This example shows an alternative way to register a global scope by overriding the model's `booted` method. The `addGlobalScope` method accepts an instance of your scope, allowing for programmatic registration. ```PHP 'London to Paris', ]); ``` -------------------------------- ### Installing Frontend Dependencies (Shell) Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/vite.md This command installs all frontend dependencies listed in the `package.json` file, which is necessary to set up Vite and the Laravel plugin in a fresh Laravel installation. ```sh npm install ``` -------------------------------- ### Scheduling Model Pruning for Specific Models in Laravel PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This example demonstrates how to schedule the `model:prune` command to prune only specific models by passing an array of model class names to the `--model` option. This allows for fine-grained control over which models are pruned. ```PHP $schedule->command('model:prune', [ '--model' => [Address::class, Flight::class], ])->daily(); ``` -------------------------------- ### Generating Eloquent Model with Migration in Shell Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This Artisan command generates a new Eloquent model class named `Flight` and simultaneously creates a corresponding database migration file. The `--migration` or `-m` option streamlines the process of setting up both the model and its database table schema. ```Shell php artisan make:model Flight --migration ``` -------------------------------- ### Manually Registering Eloquent Observer in Service Provider Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This PHP code shows how to manually register an Eloquent observer by calling the `observe` method on the model within the `boot` method of a service provider, typically `EventServiceProvider`. This approach explicitly links the `UserObserver` to the `User` model for event handling. ```PHP use AppModelsUser; use AppObserversUserObserver; /** * Register any events for your application. */ public function boot(): void { User::observe(UserObserver::class); } ``` -------------------------------- ### Muting All Model Events with withoutEvents in Laravel PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This example shows how to temporarily disable all model events for a block of code using the `withoutEvents` method. It accepts a closure, and any model operations within this closure will not dispatch events. The method returns the value returned by the closure. ```PHP use App\Models\User; $user = User::withoutEvents(function () { User::findOrFail(1)->delete(); return User::find(2); }); ``` -------------------------------- ### Defining a Basic Eloquent Model in PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This is a basic Eloquent model class for `Flight`. All Eloquent models extend `Illuminate\Database\Eloquent\Model` and typically reside in the `App\Models` namespace. This class serves as the foundation for interacting with the `flights` database table by convention. ```PHP orWhere(function (Builder $query) { $query->active(); })->get(); ``` -------------------------------- ### Performing Single Upsert with updateOrCreate in Laravel Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This example demonstrates the `updateOrCreate` method, which updates an existing model if a match is found based on the first array of attributes, or creates a new model by merging both argument arrays if no match exists. This method automatically persists the model, eliminating the need for a separate `save` call. ```PHP $flight = Flight::updateOrCreate( ['departure' => 'Oakland', 'destination' => 'San Diego'], ['price' => 99, 'discounted' => 1] ); ``` -------------------------------- ### Adding Query Parameters to GET Request in Laravel HTTP Client Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/http-client.md This example demonstrates passing an array of key/value pairs as the second argument to the `get` method. These pairs are automatically converted into URL query parameters for the GET request. ```php $response = Http::get('http://example.com/users', [ 'name' => 'Taylor', 'page' => 1, ]); ``` -------------------------------- ### Generating Eloquent Model with Associated Classes in Shell Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md These commands demonstrate how to generate an Eloquent model along with various related classes such as factories, seeders, controllers, policies, and form requests. Options can be combined, and shortcuts like `-f`, `-s`, `-c`, `-p`, `-r`, `-R`, and `--all` are available for convenience, allowing for rapid scaffolding of related components. ```Shell # Generate a model and a FlightFactory class... php artisan make:model Flight --factory php artisan make:model Flight -f # Generate a model and a FlightSeeder class... php artisan make:model Flight --seed php artisan make:model Flight -s # Generate a model and a FlightController class... php artisan make:model Flight --controller php artisan make:model Flight -c # Generate a model, FlightController resource class, and form request classes... php artisan make:model Flight --controller --resource --requests php artisan make:model Flight -crR # Generate a model and a FlightPolicy class... php artisan make:model Flight --policy # Generate a model and a migration, factory, seeder, and controller... php artisan make:model Flight -mfsc # Shortcut to generate a model, migration, factory, seeder, policy, controller, and form requests... php artisan make:model Flight --all # Generate a pivot model... php artisan make:model Member --pivot php artisan make:model Member -p ``` -------------------------------- ### Publishing a Podcast with Real-Time Facades (PHP) Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/facades.md This snippet refactors the `Podcast` model to use a real-time facade for the `Publisher` contract. By prefixing the import with `Facades\`, the `Publisher` instance is resolved from the service container, eliminating the need to explicitly pass it to the `publish` method while retaining testability. ```PHP update(['publishing' => now()]); $publisher->publish($this); // [tl! remove] Publisher::publish($this); // [tl! add] } } ``` -------------------------------- ### Retrieving Subset of Session Data in Laravel Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/session.md These examples show how to retrieve specific subsets of session data using the `only` method to get specified keys or the `except` method to get all keys except those specified. ```PHP $data = $request->session()->only(['username', 'email']); $data = $request->session()->except(['username', 'email']); ``` -------------------------------- ### Checking Node and NPM Versions (Shell) Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/vite.md This snippet shows how to verify the installed versions of Node.js and NPM using the command line. These are prerequisites for running Vite and the Laravel plugin. ```sh node -v npm -v ``` -------------------------------- ### Retrieving Model Aggregates with `count` - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Uses the Eloquent `count` aggregate method to get the number of `Flight` models where the `active` attribute is `1`. This returns a scalar value, not a model instance. ```PHP $count = Flight::where('active', 1)->count(); ``` -------------------------------- ### Retrieving Single Eloquent Models - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Shows various methods for retrieving a single Eloquent model: `find` by primary key, `first` to get the first matching record, and `firstWhere` as a shorthand for `where(...)->first()`. ```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); ``` -------------------------------- ### Processing Large Datasets with Eloquent Chunk - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Illustrates using the `chunk` method to process a large number of Eloquent models in smaller batches, reducing memory consumption. It retrieves 200 records at a time and passes them to a closure for processing. ```PHP use App\Models\Flight; use Illuminate\Database\Eloquent\Collection; Flight::chunk(200, function (Collection $flights) { foreach ($flights as $flight) { // ... } }); ``` -------------------------------- ### Installing Laravel Horizon via Composer Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/horizon.md This command installs the Laravel Horizon package into your Laravel project using Composer. It adds Horizon's dependencies and core files, making it available for further setup and configuration. ```shell composer require laravel/horizon ``` -------------------------------- ### Viewing Application Overview with Artisan Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/configuration.md This command provides a quick overview of the application's configuration, drivers, and environment, useful for debugging and understanding the current setup. ```shell php artisan about ``` -------------------------------- ### Performing a Hard Reset of Valet Installation - Shell Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/valet.md In rare cases where a simple reset doesn't work, this command performs a 'hard reset' by completely uninstalling Valet, including its configuration files and services. It should be followed by `valet install` for a fresh setup. ```Shell valet uninstall --force ``` -------------------------------- ### Starting Laravel Octane with File Watcher Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/octane.md This command starts the Octane server and enables automatic restarts upon detecting file changes within the application. This feature requires Node.js and the Chokidar file-watching library to be installed, and watched directories can be configured in `config/octane.php`. ```shell php artisan octane:start --watch ``` -------------------------------- ### Creating On-Demand Storage Disk (PHP) Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/filesystem.md Shows how to create a storage disk instance at runtime using the `Storage::build` method. This allows defining a disk configuration dynamically without needing to pre-configure it in the `filesystems` configuration file. The example creates a local disk and then stores a file on it. ```PHP use Illuminate\Support\Facades\Storage; $disk = Storage::build([ 'driver' => 'local', 'root' => '/path/to/root', ]); $disk->put('image.jpg', $content); ``` -------------------------------- ### Installing Chokidar for Octane File Watching Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/octane.md This command installs the Chokidar file-watching library as a development dependency. Chokidar is required for the `--watch` flag functionality of the `octane:start` command, allowing the Octane server to automatically restart when application files are modified. ```shell npm install --save-dev chokidar ``` -------------------------------- ### Installing PHP Event Loop Extensions for Reverb Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/reverb.md These PECL commands install alternative PHP extensions (`ext-event`, `ext-ev`, or `ext-uv`) that provide more scalable event loops than the default `stream_select`. Installing one of these is crucial for Reverb to handle more than 1,000 concurrent WebSocket connections in production environments. ```sh pecl install event # or pecl install ev # or pecl install uv ``` -------------------------------- ### Publishing a Podcast with Dependency Injection (PHP) Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/facades.md This snippet demonstrates a `Podcast` model's `publish` method using traditional dependency injection. It requires a `Publisher` instance to be explicitly passed, allowing for easy testing by mocking the injected dependency but requiring the instance on every call. ```PHP update(['publishing' => now()]); $publisher->publish($this); } } ``` -------------------------------- ### Installing Laravel Folio Service Provider (Artisan) Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/folio.md After installing the Folio package, this Artisan command publishes Folio's service provider, which registers the default directory (`resources/views/pages`) where Folio will search for routes and pages. ```bash php artisan folio:install ``` -------------------------------- ### Running Reverb Installation Command Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/reverb.md After installing the Reverb package, this Artisan command publishes the configuration file, adds necessary environment variables, and enables event broadcasting in your Laravel application, preparing it for real-time communication. ```sh php artisan reverb:install ``` -------------------------------- ### Selecting Data with Eloquent Subquery - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Demonstrates using `addSelect` with a subquery to retrieve related information in a single query. It selects all destinations and 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(); ``` -------------------------------- ### Example of Corrected Dev Server URL Output (HTML) Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/vite.md This HTML snippet illustrates the effect of using `transformOnServe` to correct dev server URLs. It shows how a relative path like `/@imagetools/...` is transformed into a full URL pointing to the Vite development server (e.g., `http://[::1]:5173/@imagetools/...`), ensuring assets are correctly loaded during development when using plugins like `vite-imagetools`. ```html - + ``` -------------------------------- ### Retrieving Model Aggregates with `max` - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Uses the Eloquent `max` aggregate method to find the maximum `price` among `Flight` models where `active` is `1`. This method returns a scalar value. ```PHP $max = Flight::where('active', 1)->max('price'); ``` -------------------------------- ### Optimizing Composer Autoloader for Production Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/deployment.md This command optimizes Composer's class autoloader map for production environments, ensuring faster class loading. It also prevents the installation of development dependencies. ```Shell composer install --optimize-autoloader --no-dev ``` -------------------------------- ### Installing Laravel Precognition Vue Helpers Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/precognition.md This shell command installs the `laravel-precognition-vue` package via NPM. This package provides the necessary frontend helpers and `useForm` function to integrate Laravel Precognition's live validation features into Vue.js applications. ```shell npm install laravel-precognition-vue ``` -------------------------------- ### Creating Stripe Setup Intent for Subscriptions Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/billing.md This PHP code shows how to create a Stripe Setup Intent using Laravel Cashier's `createSetupIntent` method. This intent is crucial for securely gathering customer payment method details for future use with subscriptions. ```PHP return view('update-payment-method', [ 'intent' => $user->createSetupIntent() ]); ``` -------------------------------- ### Inspecting Eloquent Model Details in Shell Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This Artisan command provides a detailed overview of a specific Eloquent model, `Flight`, including its attributes and relationships. It's useful for quickly understanding a model's structure and available properties without manually inspecting the model's source code. ```Shell php artisan model:show Flight ``` -------------------------------- ### Installing Laravel Precognition React Frontend Helpers (NPM) Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/precognition.md This command installs the necessary frontend helpers for integrating Laravel Precognition with React applications. It's a prerequisite for using the `useForm` hook and other Precognition functionalities in React. ```Shell npm install laravel-precognition-react ``` -------------------------------- ### Testing Real-Time Facades in Laravel (PHP) Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/facades.md This test case demonstrates how to mock a real-time facade using Laravel's `shouldReceive` helper. It verifies that the `publish` method of the `Publisher` facade is called exactly once with the `Podcast` instance, ensuring the real-time facade's behavior can be tested in isolation. ```PHP create(); Publisher::shouldReceive('publish')->once()->with($podcast); $podcast->publish(); } } ``` -------------------------------- ### Removing Anonymous Global Scope by Name in Laravel PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This snippet demonstrates how to remove a global scope that was defined using a closure. You pass the string name that was assigned to the global scope when it was registered to the `withoutGlobalScope` method. ```PHP User::withoutGlobalScope('ancient')->get(); ``` -------------------------------- ### Example of Vite Asset URL with Custom Base URL Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/vite.md This snippet illustrates the expected output of a Vite-compiled asset URL when a custom `ASSET_URL` is configured. The specified base URL (e.g., `https://cdn.example.com`) is prepended to the asset's path, demonstrating how assets are served from an external domain. ```text https://cdn.example.com/build/assets/app.9dce8d17.js ``` -------------------------------- ### Replicating Eloquent Models Excluding Attributes in Laravel PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This snippet shows how to use the `replicate` method while excluding specific attributes from being copied to the new model instance. You pass an array of attribute names that should not be replicated. ```PHP $flight = Flight::create([ 'destination' => 'LAX', 'origin' => 'LHR', 'last_flown' => '2020-03-04 11:00:00', 'last_pilot_id' => 747, ]); $flight = $flight->replicate([ 'last_flown', 'last_pilot_id' ]); ``` -------------------------------- ### Checking if a Laravel Model is Soft Deleted Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This snippet demonstrates how to check if a given Laravel Eloquent model instance has been soft deleted. The `trashed()` method returns a boolean indicating whether the `deleted_at` attribute is set. ```PHP if ($flight->trashed()) { // ... } ``` -------------------------------- ### Installing Supervisor on Ubuntu (Shell) Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/queues.md This command installs Supervisor, a process monitor for Linux, on Ubuntu systems. Supervisor is used to automatically restart queue:work processes if they fail, ensuring continuous operation. ```shell sudo apt-get install supervisor ``` -------------------------------- ### Retrieving Original Model Attributes with `getOriginal` - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Shows how to use the `getOriginal` method to retrieve the model's attributes as they were when it was initially retrieved from the database, before any modifications. It can return a single original attribute or all original attributes. ```PHP $user = User::find(1); $user->name; // John $user->email; // john@example.com $user->name = "Jack"; $user->name; // Jack $user->getOriginal('name'); // John $user->getOriginal(); // Array of original attributes... ``` -------------------------------- ### Creating Eloquent Observer using Artisan Command Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This shell command uses the Laravel Artisan tool to generate a new Eloquent observer class named `UserObserver`. The `--model=User` flag automatically populates the observer with methods for common model events, pre-configured to handle the `User` model. ```Shell php artisan make:observer UserObserver --model=User ``` -------------------------------- ### Filtering Eloquent Cursor Results - PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md Shows how to apply collection methods, like `filter`, to the `LazyCollection` returned by `cursor`. This allows for chained operations while maintaining memory efficiency by processing models one at a time. ```PHP use App\Models\User; $users = User::cursor()->filter(function (User $user) { return $user->id > 500; }); foreach ($users as $user) { echo $user->id; } ``` -------------------------------- ### Installing Laravel Precognition React Inertia Helpers (NPM) Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/precognition.md This command installs the specific frontend helpers for integrating Laravel Precognition with React applications that use Inertia.js. It's a prerequisite for using the Inertia-compatible `useForm` hook. ```Shell npm install laravel-precognition-react-inertia ``` -------------------------------- ### Starting the Laravel Reverb Server Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/reverb.md This Artisan command initiates the Reverb WebSocket server. By default, it binds to `0.0.0.0:8080`, making it accessible from all network interfaces. This is the primary command to run the Reverb service. ```sh php artisan reverb:start ``` -------------------------------- ### Running Vite Development and Build Commands Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/vite.md These shell commands are used to manage Vite's operation. `npm run dev` starts the development server with Hot Module Replacement, while `npm run build` compiles and versions assets for production deployment, optimizing them for performance. ```shell # Run the Vite development server... npm run dev # Build and version the assets for production... npm run build ``` -------------------------------- ### Defining Mass Prunable Models with Eloquent in PHP Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/eloquent.md This snippet shows how to use the `MassPrunable` trait for models. When this trait is used, models are deleted using mass-deletion queries, which is more efficient but bypasses the `pruning` method and model events. ```PHP subMonth()); } } ``` -------------------------------- ### Customizing `suggest` with Placeholder, Default, and Hint in Laravel Prompts (PHP) Source: https://github.com/sprklinginfo/laravel-10.x-docs/blob/10.x/prompts.md This example demonstrates how to enhance the `suggest` prompt by providing a `label`, `options`, `placeholder` text, a `default` value, and an informational `hint`. These arguments improve the user experience and provide context for the input. ```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.' ); ```