### Installing Laravel via Global Installer and Serving Application Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/installation.md This snippet first installs the Laravel Installer globally via Composer. Then, it uses the `laravel new` command to create a new project, navigates into it, and starts the local development server using `php artisan serve`. ```bash composer global require laravel/installer laravel new example-app cd example-app php artisan serve ``` -------------------------------- ### Creating New Laravel Project with Sail (Linux) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/installation.md This command uses `curl` to fetch a setup script from `laravel.build` and pipes it to `bash` to create a new Laravel application. It's designed for Linux users with Docker Compose installed, simplifying the initial project setup. ```bash curl -s https://laravel.build/example-app | bash ``` -------------------------------- ### Creating a New Laravel Project with Sail Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/installation.md This command initiates the creation of a new Laravel application using Laravel Sail. It leverages `curl` to fetch a setup script from `laravel.build` and pipes it to `bash` for execution. The `example-app` part of the URL can be customized to name your project directory, which will be created in the current working directory. This process requires Docker Desktop to be installed and running on either macOS or Windows (with WSL2). ```Shell curl -s "https://laravel.build/example-app" | bash ``` -------------------------------- ### Installing Laravel via Composer and Serving Application Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/installation.md This method uses Composer to create a new Laravel project. After creation, it navigates into the project directory and starts Laravel's built-in development server using the `php artisan serve` command, making the application accessible locally. ```bash composer create-project laravel/laravel:^8.0 example-app cd example-app php artisan serve ``` -------------------------------- ### Example Database Connection URL Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/database.md This snippet provides an example of a database connection URL, which encapsulates all connection information (driver, username, password, host, port, database, and options) in a single string. Laravel can parse such URLs to configure database connections. ```text mysql://root:password@127.0.0.1/forge?charset=UTF-8 ``` -------------------------------- ### Defining Parallel Testing Hooks in Laravel Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/testing.md Provides an example of using the `ParallelTesting` facade within a Laravel service provider to define custom `setUp` and `tearDown` hooks for processes, test cases, and test database creation. These hooks allow for preparing and cleaning up resources safely in parallel environments, such as seeding databases. ```PHP name = $request->name; $flight->save(); } } ``` -------------------------------- ### Example PHPUnit Unit Test Class in Laravel Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/testing.md This is a basic example of a PHPUnit unit test class in Laravel. It extends `PHPUnit\Framework\TestCase` and includes a simple test method `test_basic_test` that asserts `true` is `true`, demonstrating the fundamental structure of a test. ```PHP assertTrue(true); } } ``` -------------------------------- ### Example SQL Query with Applied Global Scope Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This SQL snippet illustrates the resulting database query after the `AncientScope` global scope has been applied to the `User` model. It shows how the `where` clause from the global scope is integrated into the final query, filtering users based on their `created_at` timestamp. ```sql select * from `users` where `created_at` < 0021-02-18 00:00:00 ``` -------------------------------- ### Beginning a Database Transaction with Laravel DB Facade - PHP Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/database.md This snippet demonstrates how to manually start a new database transaction using the `beginTransaction` method of the `DB` facade in Laravel. It requires the `Illuminate\Support\Facades\DB` dependency. This method allows for explicit control over transaction boundaries. ```PHP use Illuminate\Support\Facades\DB; DB::beginTransaction(); ``` -------------------------------- ### Passing Arguments to Artisan Test Command Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/testing.md Illustrates how to pass standard PHPUnit arguments, such as `--testsuite` and `--stop-on-failure`, to the `artisan test` command for more granular control over which tests are executed and how results are reported. ```Bash php artisan test --testsuite=Feature --stop-on-failure ``` -------------------------------- ### Enabling and Disabling Services in Homestead.yaml Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/homestead.md This YAML configuration snippet illustrates how to customize which services are enabled or disabled during Homestead provisioning. Services listed under `enabled` will be started, while those under `disabled` will be stopped. This example enables PostgreSQL and disables MySQL. ```YAML services: - enabled: - "postgresql" - disabled: - "mysql" ``` -------------------------------- ### Executing Basic SELECT Queries with DB Facade in Laravel (Controller) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/database.md This PHP example shows how to perform a basic SELECT query using Laravel's `DB` facade within a controller method. It demonstrates fetching active users with a parameterized query, which protects against SQL injection. The `select` method returns an array of `stdClass` objects, each representing a database record. ```PHP $users]); } } ``` -------------------------------- ### Specifying Number of Parallel Processes Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/testing.md Demonstrates how to explicitly set the number of parallel processes for test execution using the `--processes` option, overriding the default behavior of using all available CPU cores. This allows for fine-tuning performance based on system resources. ```Bash php artisan test --parallel --processes=4 ``` -------------------------------- ### Verifying All Required Scopes on a Route in Laravel Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md This example shows how to apply the 'scopes' middleware to a route to ensure that the incoming request's access token possesses *all* of the specified scopes (e.g., 'check-status' AND 'place-orders') before allowing access. ```PHP Route::get('/orders', function () { // Access token has both "check-status" and "place-orders" scopes... })->middleware(['auth:api', 'scopes:check-status,place-orders']); ``` -------------------------------- ### Executing UPDATE Statements with DB Facade in Laravel Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/database.md This example demonstrates how to update existing records in a database table using Laravel's `DB::update` method. It takes the SQL UPDATE query and an array of bindings, returning the count of rows that were affected by the update operation. ```PHP use Illuminate\Support\Facades\DB; $affected = DB::update( 'update users set votes = 100 where name = ?', ['Anita'] ); ``` -------------------------------- ### Recreating Parallel Test Databases Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/testing.md Shows how to force the re-creation of test databases for parallel processes using the `--recreate-databases` option. By default, these databases persist between test runs to speed up subsequent invocations, but this option ensures a fresh state. ```Bash php artisan test --parallel --recreate-databases ``` -------------------------------- ### Creating Laravel Project with Specific Sail Services Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/installation.md This command allows specifying desired services (e.g., `mysql`, `redis`) for the `docker-compose.yml` file using the `with` query string. If no services are specified, a default set is configured. ```bash curl -s "https://laravel.build/example-app?with=mysql,redis" | bash ``` -------------------------------- ### Running Tests in Parallel with Artisan Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/testing.md Explains how to significantly reduce test execution time by running tests simultaneously across multiple processes using the `--parallel` option with the `artisan test` command. This feature requires the `nunomaduro/collision` package version `^5.3` or greater. ```Bash php artisan test --parallel ``` -------------------------------- ### Creating OAuth2 Clients with Artisan Command - PHP Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md This command provides a simple way to create OAuth2 clients for testing purposes. It prompts the user for client details and outputs a client ID and secret. It's ideal for development and initial setup. ```bash php artisan passport:client ``` -------------------------------- ### Creating Personal Access Tokens with Laravel Passport (PHP) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md Demonstrates how to issue personal access tokens for a user using the `createToken` method on the `App\Models\User` model. It shows examples of creating tokens both without and with specified scopes, returning the `accessToken` property. ```PHP use App\Models\User; $user = User::find(1); // Creating a token without scopes... $token = $user->createToken('Token Name')->accessToken; // Creating a token with scopes... $token = $user->createToken('My Token', ['place-orders'])->accessToken; ``` -------------------------------- ### Accessing Parallel Testing Token Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/testing.md Illustrates how to retrieve the unique string identifier (token) for the current parallel test process using `ParallelTesting::token()`. This token can be used to segment resources or differentiate operations across different parallel test processes, for example, in database naming. ```PHP $token = ParallelTesting::token(); ``` -------------------------------- ### Executing SELECT Queries with Named Bindings in Laravel Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/database.md This example demonstrates using named bindings (e.g., `:id`) instead of positional placeholders (`?`) for parameters in `DB::select` queries. Named bindings improve readability for queries with multiple parameters and are passed as an associative array, mapping parameter names to their values. ```PHP $results = DB::select('select * from users where id = :id', ['id' => 1]); ``` -------------------------------- ### Defining Envoy Setup Block with PHP Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/envoy.md The `@setup` directive allows you to execute arbitrary PHP code before any Envoy tasks are run. This example demonstrates initializing a `DateTime` object, which can be useful for setting up variables, performing conditional logic, or preparing data needed by subsequent tasks. ```PHP @setup $now = new DateTime; @endsetup ``` -------------------------------- ### Setting Up a New Laravel Application Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/starter-kits.md This snippet demonstrates how to create a new Laravel application using `laravel.build`, navigate into the project directory, and run initial database migrations. It's a prerequisite for installing Laravel Breeze. ```bash curl -s https://laravel.build/example-app | bash cd example-app php artisan migrate ``` -------------------------------- ### Creating Public GitHub Repository for Laravel Project Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/installation.md This command extends the `--github` flag by passing additional options to the GitHub CLI, specifically `--public`, to create a public GitHub repository instead of a private one. ```bash laravel new example-app --github="--public" ``` -------------------------------- ### Generating Eloquent Model with All Related Classes in Bash Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This Artisan command is a convenient shortcut to generate an Eloquent model, migration, factory, seeder, policy, controller, and form requests. The `--all` option simplifies the creation of all commonly associated files with a single command. ```bash php artisan make:model Flight --all ``` -------------------------------- ### Running Passport Database Migrations Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md After installing Passport, this Artisan command runs the package's database migrations. These migrations create the necessary tables for storing OAuth2 clients and access tokens in your application's database. ```Shell php artisan migrate ``` -------------------------------- ### Generating Eloquent Model with Seeder in Bash Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This Artisan command generates an Eloquent model and a corresponding seeder class. Seeders are used to populate your database with initial data. Both `--seed` and its shorthand `-s` achieve the same result. ```bash php artisan make:model Flight --seed ``` ```bash php artisan make:model Flight -s ``` -------------------------------- ### Registering Query Listener in Laravel Service Provider (PHP) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/database.md This code demonstrates how to register a closure that will be invoked for every SQL query executed by your application. This is typically done in the `boot` method of a service provider and is useful for logging or debugging database queries. ```PHP sql; // $query->bindings; // $query->time; }); } } ``` -------------------------------- ### Installing Laravel Passport via Composer Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md This command installs the Laravel Passport package using Composer, making it available for use in your Laravel application. It's the first step in setting up OAuth2 authentication. ```Shell composer require laravel/passport ``` -------------------------------- ### Installing Laravel Breeze with API Stack Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/starter-kits.md This command installs Laravel Breeze with an API-only authentication scaffolding, suitable for modern JavaScript frontends like Next.js or Nuxt. It sets up the backend authentication routes and runs database migrations. ```bash php artisan breeze:install api php artisan migrate ``` -------------------------------- ### Generating Eloquent Model with Controller in Bash Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This Artisan command generates an Eloquent model and a corresponding controller class. Controllers handle incoming HTTP requests and define the application's logic. Both `--controller` and its shorthand `-c` achieve the same result. ```bash php artisan make:model Flight --controller ``` ```bash php artisan make:model Flight -c ``` -------------------------------- ### Installing Laravel Breeze with Blade Stack Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/starter-kits.md This sequence of commands installs the default Blade-based authentication scaffolding for Laravel Breeze, compiles assets using npm, and runs database migrations. It publishes views, routes, and controllers to the application. ```bash php artisan breeze:install npm install npm run dev php artisan migrate ``` -------------------------------- ### Creating GitHub Repository under Organization Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/installation.md This command allows creating the GitHub repository under a specified organization using the `--organization` flag, in addition to making it public. Requires appropriate GitHub CLI authentication and permissions for the organization. ```bash laravel new example-app --github="--public" --organization="laravel" ``` -------------------------------- ### Starting Laravel Sail Containers Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/sail.md This command initiates the Docker containers defined by Sail's `docker-compose.yml` file, bringing up the entire development environment. It's the fundamental step to run your Laravel application with Sail after installation and configuration. ```bash ./vendor/bin/sail up ``` -------------------------------- ### Retrying Laravel Database Transactions on Deadlock (PHP) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/database.md This example demonstrates how to configure `DB::transaction` to automatically retry a transaction a specified number of times if a deadlock occurs. If all retries are exhausted, an exception will be thrown. ```PHP use Illuminate\Support\Facades\DB; DB::transaction(function () { DB::update('update users set votes = 1'); DB::delete('delete from posts'); }, 5); ``` -------------------------------- ### Publishing Passport Configuration File (Artisan) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md This command publishes Passport's configuration file to your application, allowing for customization of its settings. It's a prerequisite for defining encryption keys as environment variables. ```Bash php artisan vendor:publish --tag=passport-config ``` -------------------------------- ### Generating an Eloquent Model in Bash Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This Artisan command generates a new Eloquent model class named 'Flight'. By default, models are placed in the `app/Models` directory and extend `Illuminate\Database\Eloquent\Model`. This is the most basic command for creating a model. ```bash php artisan make:model Flight ``` -------------------------------- ### Installing Laravel Breeze Composer Package Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/starter-kits.md This command installs the Laravel Breeze package via Composer. It's the first step after setting up a new Laravel application before running the `breeze:install` Artisan command. ```bash composer require laravel/breeze:1.9.2 ``` -------------------------------- ### Installing Passport with UUID Client Keys Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md This Artisan command installs Passport, instructing it to use UUIDs instead of auto-incrementing integers for the `Client` model's primary keys. This provides an alternative primary key strategy for Passport clients. ```Shell php artisan passport:install --uuids ``` -------------------------------- ### Removing All Global Scopes from a Laravel Query Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This example shows how to remove all currently applied global scopes from an Eloquent query. Calling `withoutGlobalScopes()` without any arguments will ensure that the subsequent query is executed without any global scope constraints. ```php User::withoutGlobalScopes()->get(); ``` -------------------------------- ### Generating Eloquent Model with Factory in Bash Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This Artisan command generates an Eloquent model and a corresponding factory class. Factories are used for generating large amounts of dummy data for testing or seeding your database. Both `--factory` and its shorthand `-f` achieve the same result. ```bash php artisan make:model Flight --factory ``` ```bash php artisan make:model Flight -f ``` -------------------------------- ### Installing Laravel Breeze with Inertia.js (Vue/React) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/starter-kits.md This snippet shows how to install Laravel Breeze with an Inertia.js frontend, allowing a choice between Vue or React. After installation, it compiles assets and runs database migrations, providing a modern SPA-like experience. ```bash php artisan breeze:install vue // Or... php artisan breeze:install react npm install npm run dev php artisan migrate ``` -------------------------------- ### Throwing ModelNotFoundException with findOrFail and firstOrFail Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This snippet illustrates `findOrFail` and `firstOrFail` methods, which retrieve a model or throw an `Illuminate\Database\Eloquent\ModelNotFoundException` if no result is found. This is useful for routes or controllers, as an uncaught exception automatically sends a 404 HTTP response. ```PHP $flight = Flight::findOrFail(1); $flight = Flight::where('legs', '>', 3)->firstOrFail(); ``` -------------------------------- ### Applying Client Credentials Middleware with Scopes (PHP) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md This snippet extends the previous example by showing how to restrict access to a route based on specific scopes when using the client credentials middleware. Only tokens with the 'check-status' and 'your-scope' will be granted access. ```PHP Route::get('/orders', function (Request $request) { ... })->middleware('client:check-status,your-scope'); ``` -------------------------------- ### Loading Passport Encryption Keys from Environment (Bash) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md Defines the private and public RSA keys for Passport within the application's environment variables. These keys are crucial for signing and verifying tokens, ensuring secure communication. ```Bash PASSPORT_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY-----" PASSPORT_PUBLIC_KEY="-----BEGIN PUBLIC KEY----- -----END PUBLIC KEY-----" ``` -------------------------------- ### Updating Existing Eloquent Model with save() - PHP Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This example shows how to update an existing record in the database. An Eloquent model is first retrieved, its attributes are modified, and then the `save()` method is called to persist the changes. The `updated_at` timestamp is automatically updated by Eloquent. ```PHP use App\Models\Flight; $flight = Flight::find(1); $flight->name = 'Paris to London'; $flight->save(); ``` -------------------------------- ### Retrieving Authenticated User's Personal Access Tokens (JavaScript) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md Shows an Axios GET request to `/oauth/personal-access-tokens` to fetch all personal access tokens created by the currently authenticated user. This is useful for displaying a list of tokens for management purposes. ```JavaScript axios.get('/oauth/personal-access-tokens') .then(response => { console.log(response.data); }); ``` -------------------------------- ### Truncating an Eloquent Model's Table (truncate) - PHP Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This example demonstrates using the static `truncate()` method on an Eloquent model to delete all records from its associated database table. This operation also resets any auto-incrementing IDs, effectively clearing the table completely. ```PHP Flight::truncate(); ``` -------------------------------- ### Retrieving Specific Scope Instances by ID with Laravel Passport (PHP) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md This example demonstrates how to use `Passport::scopesFor()` to retrieve an array of `Laravel\Passport\Scope` instances that match a given array of scope IDs or names, allowing you to fetch specific scope definitions. ```PHP Passport::scopesFor(['place-orders', 'check-status']); ``` -------------------------------- ### Configuring Multiple Passport Authentication Guards (PHP) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md Provides an example of defining multiple authentication guards in `config/auth.php` for different user providers. This allows an application to authenticate various types of users, such as `users` and `customers`, using separate Passport drivers. ```PHP 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], 'api-customers' => [ 'driver' => 'passport', 'provider' => 'customers', ], ``` -------------------------------- ### Generating Eloquent Model with Policy in Bash Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This Artisan command generates an Eloquent model and a corresponding policy class. Policies are used to organize authorization logic for a given model or resource. The `--policy` option is used for this purpose. ```bash php artisan make:model Flight --policy ``` -------------------------------- ### Configuring GitHub Actions for Laravel Dusk Tests Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/dusk.md This GitHub Actions workflow defines steps to run Laravel Dusk tests. It covers checking out the repository, preparing the environment, creating a database, installing Composer dependencies, generating an application key, upgrading and starting the Chrome driver, running the Laravel development server, executing Dusk tests, and uploading screenshots/console logs on failure. ```YAML name: CI on: [push] jobs: dusk-php: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - 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 `/opt/google/chrome/chrome --version | cut -d " " -f3 | cut -d "." -f1` - name: Start Chrome Driver run: ./vendor/laravel/dusk/bin/chromedriver-linux & - name: Run Laravel Server run: php artisan serve --no-reload & - name: Run Dusk Tests env: APP_URL: "http://127.0.0.1:8000" run: php artisan dusk - name: Upload Screenshots if: failure() uses: actions/upload-artifact@v2 with: name: screenshots path: tests/Browser/screenshots - name: Upload Console Logs if: failure() uses: actions/upload-artifact@v2 with: name: console path: tests/Browser/console ``` -------------------------------- ### Deleting Eloquent Models by Multiple Primary Keys (destroy) - PHP Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This example illustrates deleting multiple Eloquent models by passing their primary keys as separate arguments to the static `destroy()` method. Each model is loaded and deleted individually, ensuring model events are dispatched. ```PHP Flight::destroy(1, 2, 3); ``` -------------------------------- ### Requesting Scopes for Authorization Code Grant in Laravel Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md This example demonstrates how an API consumer requests desired scopes when using the authorization code grant. The scopes are specified as a space-delimited list in the 'scope' query string parameter during the redirect to the OAuth authorization endpoint. ```PHP Route::get('/redirect', function () { $query = http_build_query([ 'client_id' => 'client-id', 'redirect_uri' => 'http://example.com/callback', 'response_type' => 'code', 'scope' => 'place-orders check-status', ]); return redirect('http://passport-app.test/oauth/authorize?'.$query); }); ``` -------------------------------- ### Retrieving All Defined Scopes via JSON API (JavaScript) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md Illustrates how to use Axios to make a GET request to the `/oauth/scopes` endpoint. This API route returns all scopes defined within the application, useful for presenting available scopes to users for token assignment. ```JavaScript axios.get('/oauth/scopes') .then(response => { console.log(response.data); }); ``` -------------------------------- ### Retrieving or Creating Models with firstOrCreate and firstOrNew Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This snippet demonstrates `firstOrCreate` and `firstOrNew` methods. `firstOrCreate` finds a record or creates it, persisting to the database. `firstOrNew` finds a record or instantiates a new model (not persisted until `save()` is called). Both accept attributes for lookup and optional attributes for creation/instantiation. ```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'] ); ``` -------------------------------- ### Retrieving All OAuth2 Clients - JavaScript (Axios) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md This Axios GET request retrieves all OAuth2 clients associated with the authenticated user. It's useful for displaying a list of clients in a user dashboard for management purposes. The response data will contain an array of client objects. ```javascript axios.get('/oauth/clients') .then(response => { console.log(response.data); }); ``` -------------------------------- ### Installing Supervisor on Ubuntu (Bash) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/horizon.md Installs the Supervisor process monitor on Ubuntu-based Linux systems using the `apt-get` package manager. Supervisor is used to automatically restart the `horizon` process if it unexpectedly stops. ```bash sudo apt-get install supervisor ``` -------------------------------- ### Disabling Auto-Incrementing Primary Key in Laravel Eloquent (PHP) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This snippet illustrates how to configure an Eloquent model to use a non-incrementing primary key. Setting public $incrementing = false; is necessary when your primary key is not an auto-incrementing integer, for example, if you are using UUIDs or custom string identifiers. ```PHP getPdo(); ``` -------------------------------- ### Basic Browser Test Example with Laravel Dusk (PHP) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/dusk.md This snippet demonstrates how to create a basic browser test using Laravel Dusk. It initializes a user, navigates to the login page, types credentials, presses the login button, and asserts the redirection to the home page. It uses `DatabaseMigrations` for a clean test environment. ```PHP create([ 'email' => 'taylor@laravel.com', ]); $this->browse(function ($browser) use ($user) { $browser->visit('/login') ->type('email', $user->email) ->type('password', 'password') ->press('Login') ->assertPathIs('/home'); }); } } ``` -------------------------------- ### Creating a Unit Test in Laravel Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/testing.md This Artisan command generates a new unit test class named `UserTest` within the `tests/Unit` directory. Unit tests focus on isolated portions of code, typically a single method, and do not boot the full Laravel application. ```PHP php artisan make:test UserTest --unit ``` -------------------------------- ### Starting Horizon via Supervisor (Bash) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/horizon.md Manually starts the `horizon` program as defined in Supervisor's configuration. This command is used to initiate the Horizon process under Supervisor's management after configuration updates. ```bash sudo supervisorctl start horizon ``` -------------------------------- ### Filtering Eloquent Cursor Results with LazyCollection in PHP Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This example demonstrates applying collection methods to results obtained via the `cursor` method. The `cursor` returns a `LazyCollection` instance, allowing methods like `filter` to be chained while still maintaining the memory efficiency of loading only one model at a time during iteration. ```php use App\Models\User; $users = User::cursor()->filter(function ($user) { return $user->id > 500; }); foreach ($users as $user) { echo $user->id; } ``` -------------------------------- ### Installing Laravel Valet Globally via Composer (Bash) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/valet.md This command installs Laravel Valet as a global Composer package, making the `valet` command available system-wide. It's a crucial step after installing Composer and PHP. ```Bash composer global require laravel/valet ``` -------------------------------- ### Customizing Timestamp Format in Laravel Eloquent Model (PHP) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This example demonstrates how to specify a custom storage format for a model's timestamp columns. Setting protected $dateFormat = 'U'; configures Eloquent to store timestamps as Unix timestamps (integers), affecting both database storage and serialization to arrays or JSON. ```PHP { console.log(response.data); }); ``` -------------------------------- ### Publishing Passport Views for Customization (Bash) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md This Artisan command publishes Passport's default Blade views, specifically the authorization approval screen, to resources/views/vendor/passport. This allows developers to fully customize the user interface presented during the OAuth authorization flow. ```Bash php artisan vendor:publish --tag=passport-views ``` -------------------------------- ### Listing All Authorized Access Tokens (JavaScript) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/passport.md This Axios GET request targets the /oauth/tokens endpoint to retrieve a list of all access tokens that the currently authenticated user has authorized. This API is typically used in a user dashboard to display active tokens, allowing users to review and manage their granted permissions. ```JavaScript axios.get('/oauth/tokens') .then(response => { console.log(response.data); }); ``` -------------------------------- ### Deleting Eloquent Models by Collection of Primary Keys (destroy) - PHP Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This example shows how to delete multiple Eloquent models by passing a Laravel Collection of primary keys to the static `destroy()` method. This method processes each ID in the collection, loading and deleting the corresponding model individually, ensuring model events are dispatched. ```PHP Flight::destroy(collect([1, 2, 3])); ``` -------------------------------- ### Sharing Valet Sites via Expose (Bash) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/valet.md This command sequence navigates to a Valet site directory and shares the site publicly using Expose. It displays a sharable URL for access on other devices or with team members. Expose must be installed on the system to use this functionality. ```Bash cd ~/Sites/laravel expose ``` -------------------------------- ### Listing Configured Valet Proxies (Bash) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/valet.md This command displays a list of all currently configured proxy sites within Valet. It provides an overview of which Valet domains are forwarding traffic to other local services, aiding in managing complex development environments. ```Bash valet proxies ``` -------------------------------- ### Chunking Eloquent Results by ID with Update in PHP Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This example uses `chunkById` to process `Flight` models where 'departed' is true, in chunks of 200. It's specifically designed for scenarios where results are filtered and then updated within the iteration, preventing inconsistent results that might occur with `chunk` due to internal ID-based retrieval. ```php Flight::where('departed', true) ->chunkById(200, function ($flights) { $flights->each->update(['departed' => false]); }, $column = 'id'); ``` -------------------------------- ### Performing Multiple Eloquent Model Upserts (upsert) - PHP Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This example illustrates the `upsert` method for performing multiple insert-or-update operations in a single query. It takes an array of records to upsert, an array of unique identifier columns (`departure`, `destination`), and an array of columns to update (`price`) if a match is found. Timestamps are automatically handled. ```PHP Flight::upsert([ ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99], ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150] ], ['departure', 'destination'], ['price']); ``` -------------------------------- ### Defining Custom Primary Key in Laravel Eloquent Model (PHP) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This example shows how to specify a custom primary key column name for an Eloquent model. By default, Eloquent assumes the primary key is named id; setting protected $primaryKey allows you to use a different column, such as flight_id, as the unique identifier for records. ```PHP password);\n }\n} ``` -------------------------------- ### Publishing Telescope Assets and Running Migrations Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/telescope.md These Artisan commands are essential post-installation steps for Laravel Telescope. `telescope:install` publishes Telescope's assets and configuration files to your application, while `migrate` creates the necessary database tables to store the collected application data, such as requests, queries, and exceptions. ```Artisan CLI php artisan telescope:install ``` ```Artisan CLI php artisan migrate ``` -------------------------------- ### Streaming Eloquent Results Lazily by ID with Update in PHP Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This example uses `lazyById` to stream `Flight` models filtered by 'departed' status, in chunks of 200, based on their `id`. It's suitable for scenarios where records are updated during iteration, ensuring consistent results by always retrieving models with an ID greater than the last processed one. ```php Flight::where('departed', true) ->lazyById(200, $column = 'id') ->each->update(['departed' => false]); ``` -------------------------------- ### Registering an Eloquent Observer in EventServiceProvider (PHP) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This PHP code demonstrates how to register an Eloquent observer. By calling the `observe` method on the `User` model and passing the `UserObserver::class`, all events for the `User` model will be routed to the `UserObserver`. This registration typically occurs within the `boot` method of the `App\Providers\EventServiceProvider`. ```PHP use App\Models\User; use App\Observers\UserObserver; /** * Register any events for your application. * * @return void */ public function boot() { User::observe(UserObserver::class); } ``` -------------------------------- ### Setting Primary Key Data Type to String in Laravel Eloquent (PHP) Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/eloquent.md This example demonstrates how to declare the data type of a model's primary key as a string. When using non-integer primary keys, such as UUIDs, setting protected $keyType = 'string'; ensures Eloquent correctly handles the primary key's type during operations like casting. ```PHP $user->createSetupIntent() ]); ``` -------------------------------- ### Installing Packages Without Overwriting Configs in Homestead Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/homestead.md This shell command is used within the `after.sh` script to install packages in Homestead without prompting to overwrite existing configuration files. It forces the use of default or old configurations, preventing conflicts with Homestead's setup. ```Shell sudo apt-get -y \\ -o Dpkg::Options::=\"--force-confdef\" \\ -o Dpkg::Options::=\"--force-confold\" \\ install package-name ``` -------------------------------- ### Publishing Fortify's Resources Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/fortify.md This Artisan command publishes Fortify's essential resources, including its actions to the `app/Actions` directory, configuration file, and database migrations. This step is crucial for customizing Fortify's behavior and setting up its database tables. ```bash php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider" ``` -------------------------------- ### Defining GET Route with Controller Action in Laravel Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/routing.md This example shows how to define a GET route that dispatches to a controller action. The `/user` URI is mapped to the `index` method of the `UserController`, a common pattern for web interface routes defined in `routes/web.php`. ```PHP use App\Http\Controllers\UserController; Route::get('/user', [UserController::class, 'index']); ``` -------------------------------- ### Creating a Basic Collection Instance Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/collections.md This code illustrates the simplest way to instantiate an `Illuminate\Support\Collection` using the `collect` helper function, passing an array as its initial data. This is the fundamental step for leveraging Laravel's collection functionalities. ```PHP $collection = collect([1, 2, 3]); ``` -------------------------------- ### Installing Sail with Devcontainer Support Source: https://github.com/dhtmdgkr123/laravel-docs-v8/blob/8.x/sail.md This Artisan command installs Sail and additionally publishes a default `.devcontainer/devcontainer.json` file. This enables seamless development within a Visual Studio Code Devcontainer environment, providing a consistent and isolated workspace. ```bash php artisan sail:install --devcontainer ```