### Install and Use Laravel Installer Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/installation.md Installs the Laravel Installer globally via Composer and uses it to create a new project. It also starts the local development server. Requires Composer and the system's PATH to be configured for Composer's vendor bin directory. ```shell composer global require laravel/installer laravel new example-app cd example-app php artisan serve ``` -------------------------------- ### Install Laravel Project via Composer Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/installation.md Installs a new Laravel project using Composer and starts the local development server using the Artisan CLI. Requires PHP and Composer to be installed. ```shell composer create-project laravel/laravel:^8.0 example-app cd example-app php artisan serve ``` -------------------------------- ### Create Laravel Project with Git Repository Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/installation.md Creates a new Laravel project and initializes a Git repository, committing the base skeleton. Requires Git to be installed and configured. ```bash laravel new example-app --git ``` -------------------------------- ### Create Laravel Project with GitHub Repository Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/installation.md Creates a new Laravel project, initializes a Git repository, and creates a corresponding private repository on GitHub. Requires GitHub CLI and Git to be installed and authenticated. ```bash laravel new example-app --github ``` -------------------------------- ### Create Public GitHub Repository for Laravel Project Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/installation.md Creates a new Laravel project and a public GitHub repository using the GitHub CLI. Requires GitHub CLI and Git to be installed and authenticated. ```bash laravel new example-app --github="--public" ``` -------------------------------- ### Create Laravel Project in GitHub Organization Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/installation.md Creates a new Laravel project and a GitHub repository under a specified organization. Requires GitHub CLI and Git to be installed and authenticated. ```bash laravel new example-app --github="--public" --organization="laravel" ``` -------------------------------- ### Create Laravel Project with Git and Custom Branch Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/installation.md Creates a new Laravel project, initializes a Git repository, and sets the initial branch name. Requires Git to be installed and configured. ```bash laravel new example-app --git --branch="main" ``` -------------------------------- ### Laravel Authentication Quickstart: Breeze, User Retrieval, and Route Protection Source: https://context7.com/dhtmdgkr123/laravel-8-docs/llms.txt Provides instructions for installing the Laravel Breeze starter kit for authentication setup, including Composer installation, artisan commands, and database migration. It demonstrates retrieving the authenticated user via Auth facade and request instance, checking authentication status, and protecting routes using the 'auth' middleware. ```php // Install Laravel Breeze starter kit composer require laravel/breeze --dev php artisan breeze:install npm install && npm run dev php artisan migrate // Retrieving authenticated user use Illuminate\Support\Facades\Auth; $user = Auth::user(); $id = Auth::id(); // Via request instance $user = $request->user(); // Check if authenticated if (Auth::check()) { // User is logged in } // Protecting routes with middleware Route::get('/profile', function () { // Only authenticated users })->middleware('auth'); // In controller constructor class UserController extends Controller { public function __construct() { $this->middleware('auth'); $this->middleware('auth:api')->only('index'); } } ``` -------------------------------- ### Create Laravel Project via Curl (macOS/Windows/Linux) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/installation.md This command downloads and executes a script to create a new Laravel project. It requires curl and bash to be installed. The project directory name can be customized in the URL. The output is a new Laravel project ready for Sail. ```shell curl -s "https://laravel.build/example-app" | bash ``` -------------------------------- ### Basic PHPUnit Test Example Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/testing.md An example of a basic unit test class using PHPUnit. It demonstrates a simple test method `test_basic_test` that asserts a boolean value. If defining custom `setUp` or `tearDown` methods, ensure to call their parent class counterparts. ```php assertTrue(true); } } ``` -------------------------------- ### Start Laravel Sail (macOS/Windows/Linux) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/installation.md Navigates to the Laravel project directory and starts the application containers using Laravel Sail. This command requires the project to be created first using the aforementioned curl command. The first run may take several minutes to build Docker images. ```shell cd example-app ./vendor/bin/sail up ``` -------------------------------- ### Create Laravel Project with Docker Compose on Linux Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/installation.md Creates a new Laravel project using Docker Compose on Linux. This command downloads a script and executes it to set up the project environment. It requires curl to be installed. ```shell curl -s https://laravel.build/example-app | bash ``` -------------------------------- ### Run Laravel Dusk Installation Artisan Command Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/dusk.md After installing the Dusk package, this Artisan command initializes Dusk by creating the necessary test directories and example test files. ```bash php artisan dusk:install ``` -------------------------------- ### Parallel Testing Hooks with ParallelTesting Facade Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/testing.md Implement setup and teardown logic for parallel test processes and test cases using the `ParallelTesting` facade. This allows for preparation of resources before tests run and cleanup afterwards. ```php [ "read" => [ "host" => [ "192.168.1.1", "196.168.1.2", ], ], "write" => [ "host" => [ "196.168.1.3", ], ], "sticky" => true, "driver" => "mysql", "database" => "database", "username" => "root", "password" => "", "charset" => "utf8mb4", "collation" => "utf8mb4_unicode_ci", "prefix" => "", ] ``` -------------------------------- ### Install Laravel Breeze with Inertia.js (Vue) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/starter-kits.md Installs Laravel Breeze with an Inertia.js frontend stack using Vue. Requires a new Laravel application, database setup, and asset compilation. ```bash php artisan breeze:install vue npm install npm run dev php artisan migrate ``` -------------------------------- ### Install Laravel Breeze with Blade and Tailwind CSS Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/starter-kits.md Installs Laravel Breeze with default Blade views styled with Tailwind CSS. Requires a new Laravel application, database setup, and asset compilation. ```bash curl -s https://laravel.build/example-app | bash cd example-app php artisan migrate ``` ```bash composer require laravel/breeze:1.9.2 ``` ```bash php artisan breeze:install npm install npm run dev php artisan migrate ``` -------------------------------- ### Run PHPUnit Tests Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/testing.md Execute tests using the PHPUnit command-line tool. This is the fundamental way to run tests defined in your Laravel application. ```bash ./vendor/bin/phpunit ``` -------------------------------- ### Run Laravel Tests with Artisan Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/testing.md Utilize the Artisan `test` command to run your application's tests. This command offers verbose output for easier debugging and supports passing PHPUnit arguments. ```bash php artisan test php artisan test --testsuite=Feature --stop-on-failure ``` -------------------------------- ### Running Tests with Artisan or PHPUnit Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/testing.md Execute your application's tests using either the `php artisan test` command or by directly running the PHPUnit binary found in the vendor directory. These commands will discover and run all defined tests. ```bash php artisan test vendor/bin/phpunit ``` -------------------------------- ### Retrieve First Model or Execute Closure - PHP Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This shows how to use the `firstOr` method to retrieve the first Eloquent model matching constraints, or execute a closure and return its result if no model is found. It requires a query constraint and a closure. The `Flight` model is used as an example. ```php use App\Models\Flight; $model = Flight::where('legs', '>', 3)->firstOr(function () { // ... }); ``` -------------------------------- ### Run General SQL Statement Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/database.md Executes a general SQL statement that does not return a value, such as 'DROP TABLE'. Use with caution as it directly manipulates the database schema. ```php DB::statement('drop table users'); ``` -------------------------------- ### Nginx Server Configuration for Laravel Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/deployment.md Example Nginx configuration file to direct all web requests to your Laravel application's public/index.php file. Ensure this configuration is tailored to your specific server setup and security requirements. ```nginx server { listen 80; listen [::]:80; server_name example.com; root /srv/example.com/public; add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; index index.php; charset utf-8; location / { try_files $uri $uri/ /index.php?$query_string; } location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } error_page 404 /index.php; location ~ \.php$ { fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; include fastcgi_params; } location ~ /\.(?!well-known).* { deny all; } } ``` -------------------------------- ### Run SELECT Query with Named Bindings (PHP) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/database.md Demonstrates executing a SELECT query using named parameter bindings instead of positional placeholders. This can improve query readability for complex queries. ```php $results = DB::select('select * from users where id = :id', ['id' => 1]); ``` -------------------------------- ### Laravel 8 Seeder Namespace Example Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/upgrade.md This example demonstrates the updated structure for a seeder class in Laravel 8, including the `Database\Seeder` namespace. The `run` method remains the primary method for seeding data. ```php get('/'); $response->assertStatus(200); } } ``` -------------------------------- ### Recreate Test Databases for Parallel Testing Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/testing.md Force the recreation of test databases when running tests in parallel. This is useful for ensuring a clean state for your tests, especially when using the `--recreate-databases` option with the Artisan `test` command. ```bash php artisan test --parallel --recreate-databases ``` -------------------------------- ### Using Cache and Route Facades in Laravel Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/facades.md Demonstrates how to use the Cache and Route facades to retrieve a value from the cache via a GET request. This example requires the Illuminate\Support\Facades\Cache and Illuminate\Support\Facades\Route namespaces. ```php use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Route; Route::get('/cache', function () { return Cache::get('key'); }); ``` -------------------------------- ### Configure SQLite Database Connection - Environment Variables Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/database.md This snippet shows how to configure a SQLite database connection using environment variables. It specifies the connection type and the absolute path to the database file. It also demonstrates how to enable foreign key constraints. ```env DB_CONNECTION=sqlite DB_DATABASE=/absolute/path/to/database.sqlite ``` ```env DB_FOREIGN_KEYS=true ``` -------------------------------- ### Register Query Listener Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/database.md Registers a closure to be executed for every SQL query run by the application. Useful for logging or debugging. The listener is typically registered in a service provider's `boot` method. ```php sql; // $query->bindings; // $query->time; }); } } ``` -------------------------------- ### SQL Query with Global Scope Applied Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This is the resulting SQL query executed when a model has the 'AncientScope' applied. It demonstrates how the `where` clause from the global scope is automatically included in the generated SQL. ```sql select * from `users` where `created_at` < 0021-02-18 00:00:00 ``` -------------------------------- ### Retrieve All Records with Eloquent Model Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This example illustrates how to retrieve all records from a database table associated with an Eloquent model using the `all` method. The method returns an `Illuminate\Database\Eloquent\Collection` instance, which can be iterated over to access individual model instances. ```php use App\Models\Flight; foreach (Flight::all() as $flight) { echo $flight->name; } ``` -------------------------------- ### Run SELECT Query with Parameter Binding (PHP) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/database.md Executes a SELECT query against the database using the DB facade with placeholder bindings. This method is secure against SQL injection. It returns an array of stdClass objects representing the fetched records. ```php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; class UserController extends Controller { /** * Show a list of all of the application's users. * * @return \Illuminate\Http\Response */ public function index() { $users = DB::select('select * from users where active = ?', [1]); return view('user.index', ['users' => $users]); } } ``` ```php use Illuminate\Support\Facades\DB; $users = DB::select('select * from users'); foreach ($users as $user) { echo $user->name; } ``` -------------------------------- ### Utilize Dynamic Eloquent Model Scopes (PHP) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md Illustrates how to call dynamic local scopes with arguments. The arguments defined in the scope method signature are passed when calling the scope. This example filters users by the 'admin' type. ```php use App\Models\User; $users = User::ofType('admin')->get(); ``` -------------------------------- ### Create Laravel User Observer with Artisan Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This snippet shows the Artisan command to generate a new observer class for the User model. It places the observer in the App/Observers directory and creates basic event handler methods. ```bash php artisan make:observer UserObserver --model=User ``` -------------------------------- ### Order By Subquery - PHP Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This example shows how to order query results based on a subquery. It sorts destinations by the arrival time of their last flight, executing the entire operation in a single database query. It utilizes the Destination and Flight models. ```php return Destination::orderByDesc( Flight::select('arrived_at') ->whereColumn('destination_id', 'destinations.id') ->orderByDesc('arrived_at') ->limit(1) )->get(); ``` -------------------------------- ### Register Laravel Observer in EventServiceProvider Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This PHP code demonstrates how to register a UserObserver with the User model within the boot method of the application's EventServiceProvider. This ensures the observer listens to model events. ```php use App\Models\User; use App\Observers\UserObserver; /** * Register any events for your application. * * @return void */ public function boot() { User::observe(UserObserver::class); } ``` -------------------------------- ### Test Model Pruning with --pretend Option Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This command-line example shows how to test the `model:prune` command using the `--pretend` option. It reports the number of records that would be pruned without actually deleting them, aiding in validation. ```bash php artisan model:prune --pretend ``` -------------------------------- ### Install Laravel Breeze with API Stack for JavaScript Applications Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/starter-kits.md Installs Laravel Breeze with an API stack, suitable for authenticating modern JavaScript applications like Next.js or Nuxt.js. Sets up a FRONTEND_URL in the .env file. ```bash php artisan breeze:install api php artisan migrate ``` -------------------------------- ### Define Dynamic Eloquent Model Scopes (PHP) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md Shows how to create dynamic local scopes in Eloquent models that accept parameters. Additional parameters are added after the $query argument in the scope method signature. This example defines a scope to filter users by a given type. ```php where('type', $type); } } ``` -------------------------------- ### Retrieve or Create Model - PHP Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This snippet demonstrates the `firstOrCreate` method, which retrieves a model by given attributes or creates it if it doesn't exist. It can also merge additional attributes for creation. It uses the `Flight` model. Inputs are attribute arrays. ```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'] ); ``` -------------------------------- ### Install Laravel Fortify Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/fortify.md Installs the Laravel Fortify package using Composer. This is the first step to integrate backend authentication features into your Laravel application. ```bash composer require laravel/fortify ``` -------------------------------- ### Insert New Model Instance with Eloquent Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md Shows how to create a new Eloquent model instance, assign attributes, and save it to the database using the save() method. The created_at and updated_at timestamps are handled automatically. ```php name = $request->name; $flight->save(); } } ``` -------------------------------- ### Share Development Environment using `share` command Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/homestead.md This command allows you to share your local Homestead development environment with others. SSH into your VM and run `share `, for example, `share homestead.test`. You can also specify Ngrok options like region or subdomain. ```bash share homestead.test ``` ```bash share homestead.test -region=eu -subdomain=laravel ``` -------------------------------- ### Define Eloquent Model Local Scopes (PHP) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md Defines local scopes within an Eloquent model to encapsulate common query constraints. Scopes are methods prefixed with 'scope' and should return a query builder instance or void. This example shows scopes for 'popular' and 'active' users. ```php where('votes', '>', 100); } /** * Scope a query to only include active users. * * @param \Illuminate\Database\Eloquent\Builder $query * @return void */ public function scopeActive($query) { $query->where('active', 1); } } ``` -------------------------------- ### Define an Anonymous Global Scope in PHP Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This example shows how to define a global scope using a closure directly within the model's `booted` method. This is suitable for simpler scopes that don't require a dedicated class. A unique name must be provided for the closure-based scope. ```php where('created_at', '<', now()->subYears(2000)); }); } } ``` -------------------------------- ### Retrieve or Instantiate New Model - PHP Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This demonstrates the `firstOrNew` method, which retrieves a model by given attributes or instantiates a new model instance if it doesn't exist. The new instance is not persisted until `save` is called. It uses the `Flight` model. Inputs are attribute arrays. ```php use App\Models\Flight; // 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'] ); ``` -------------------------------- ### Refresh Eloquent Model Instance Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This example demonstrates how to refresh an existing Eloquent model instance using the `fresh` and `refresh` methods. `fresh` re-retrieves the model from the database without altering the current instance, while `refresh` re-hydrates the existing instance with the latest data, including its relationships. ```php $flight = Flight::where('number', 'FR 900')->first(); $freshFlight = $flight->fresh(); $flight = Flight::where('number', 'FR 900')->first(); $flight->number = 'FR 456'; $flight->refresh(); $flight->number; // "FR 900" ``` -------------------------------- ### Create Browser Instance for Login Test (PHP) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/dusk.md Demonstrates creating a browser instance using the `browse` method to perform a login test. It navigates to the login page, enters credentials, submits the form, and asserts the user is redirected to the home page. Requires `LaravelDuskChrome` and uses `DatabaseMigrations` trait. ```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'); }); } } ``` -------------------------------- ### Install Laravel Passport Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/passport.md Install the Laravel Passport package using Composer. This command fetches and installs the necessary files for Passport. ```bash composer require laravel/passport ``` -------------------------------- ### Install Laravel Telescope Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/telescope.md Installs the Laravel Telescope package using Composer. This command is used for both standard and local-only installations. ```bash composer require laravel/telescope ``` ```bash composer require laravel/telescope --dev ``` -------------------------------- ### GitHub Actions Configuration for Laravel Dusk Tests Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/dusk.md This snippet outlines the GitHub Actions workflow configuration for running Laravel Dusk tests. It details steps for checking out code, preparing the environment, setting up a database, installing dependencies, and running Dusk tests. ```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 ``` -------------------------------- ### Configure Database Connection Using URL - Laravel Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/database.md This snippet illustrates how to configure a database connection using a single database URL, which encapsulates all connection details. This is an alternative to specifying individual configuration options and can be set via the `url` configuration option or the `DATABASE_URL` environment variable. ```html mysql://root:password@127.0.0.1/forge?charset=UTF-8 ``` ```html driver://username:password@host:port/database?options ``` -------------------------------- ### Publish Fortify Resources Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/fortify.md Publishes Fortify's actions, configuration file, and migrations to your Laravel project. This command makes Fortify's components available for customization and use. ```bash php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider" ``` -------------------------------- ### PHP Custom Cast Implementation in Laravel Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent-mutators.md Provides an example of creating a custom cast class in Laravel by implementing the `CastsAttributes` interface. The example re-implements the built-in 'json' cast, demonstrating the `get` and `set` methods. ```php { console.log(response.data); }); ``` -------------------------------- ### Equivalent View Creation: Facade vs. Helper Function (PHP) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/facades.md Demonstrates the identical functionality of using the View facade and the `view` helper function to create a view. Both methods achieve the same result of rendering a view named 'profile'. ```PHP return Illuminate\Support\Facades\View::make('profile'); return view('profile'); ``` -------------------------------- ### Install Legacy Model Factories Package (Composer) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/upgrade.md To continue using existing model factories with Laravel 8.x, install the `laravel/legacy-factories` package using Composer. This package ensures compatibility with Laravel 7.x style factories during the upgrade process. ```bash composer require laravel/legacy-factories ``` -------------------------------- ### Serving Sites with Valet Park Command Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/valet.md The 'park' command registers a directory for Valet to serve all applications within it. Applications are accessible via `http://.test`. ```bash cd ~/Sites valet park ``` -------------------------------- ### Publish Telescope Assets and Run Migrations Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/telescope.md Publishes Telescope's assets and runs the database migrations required to store Telescope's data. These commands are essential after installing Telescope. ```bash php artisan telescope:install php artisan migrate ``` -------------------------------- ### GET /oauth/tokens Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/passport.md Retrieves a list of all authorized access tokens for the authenticated user. This is useful for displaying tokens to the user for management. ```APIDOC ## GET /oauth/tokens ### Description Retrieves a list of all authorized access tokens for the authenticated user. This is useful for displaying tokens to the user for management. ### Method GET ### Endpoint `/oauth/tokens` ### Parameters None ### Request Example ```javascript axios.get('/oauth/tokens') .then(response => { console.log(response.data); }); ``` ### Response #### Success Response (200) - An array of token objects, each containing details about the token. #### Response Example ```json [ { "id": 1, "name": "My App Token", "scopes": ["*"], "revoked": false, "created_at": "2023-10-27T10:00:00.000000Z", "updated_at": "2023-10-27T10:00:00.000000Z" } ] ``` ``` -------------------------------- ### Get All Clients Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/passport.md Retrieves a list of all OAuth2 clients associated with the authenticated user. This is useful for displaying clients in a dashboard for management. ```APIDOC ## GET /oauth/clients ### Description This route returns all of the clients for the authenticated user. This is primarily useful for listing all of the user's clients so that they may edit or delete them. ### Method GET ### Endpoint /oauth/clients ### Parameters #### Query Parameters None ### Request Example ```javascript axios.get('/oauth/clients') .then(response => { console.log(response.data); }); ``` ### Response #### Success Response (200) - **clients** (array) - An array of client objects. - **id** (integer) - The unique identifier of the client. - **name** (string) - The name of the client. - **redirect_uri** (string) - The redirect URI configured for the client. - **secret** (string) - The client secret. - **created_at** (datetime) - The timestamp when the client was created. - **updated_at** (datetime) - The timestamp when the client was last updated. #### Response Example ```json { "data": [ { "id": 1, "name": "My First Client", "redirect_uri": "http://example.com/callback", "secret": "some_secret_string", "created_at": "2023-10-27T10:00:00.000000Z", "updated_at": "2023-10-27T10:00:00.000000Z" } ] } ``` ``` -------------------------------- ### Install Laravel Sanctum Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/sanctum.md Installs the Laravel Sanctum package using Composer. This is the first step to enabling Sanctum's authentication features. ```bash composer require laravel/sanctum ``` -------------------------------- ### Create Subscription with Coupon Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/cashier-paddle.md This PHP example shows how to apply a coupon when creating a subscription. The `withCoupon` method is chained before the `create` method, accepting the coupon code as an argument. ```php $payLink = $user->newSubscription('default', $monthly = 12345) ->returnTo(route('home')) ->withCoupon('code') ->create(); ``` -------------------------------- ### Handle Deadlocks In Transactions Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/database.md Retries a database transaction up to a specified number of times when a deadlock occurs. If all retries fail, an exception is thrown. ```php use Illuminate\Support\Facades\DB; DB::transaction(function () { DB::update('update users set votes = 1'); DB::delete('delete from posts'); }, 5); ``` -------------------------------- ### Install Supervisor on Ubuntu Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/horizon.md Installs the Supervisor process control system on Ubuntu using the apt-get package manager. Supervisor is essential for automatically restarting the Horizon process if it fails. ```shell sudo apt-get install supervisor ``` -------------------------------- ### Access Specific Database Connection Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/database.md Retrieves records from a specific database connection using its name. Assumes the connection is configured in `config/database.php`. ```php use Illuminate\Support\Facades\DB; $users = DB::connection('sqlite')->select(...); ``` -------------------------------- ### Start Octane Server with File Watching Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/octane.md Instructs Laravel Octane to automatically restart the server when changes are detected in application files. Requires Node.js and the Chokidar library to be installed. ```bash php artisan octane:start --watch ``` -------------------------------- ### Configure Fortify Features Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/fortify.md Defines which backend authentication features Fortify will expose. This example enables registration, password reset, and email verification. ```php 'features' => [ Features::registration(), Features::resetPasswords(), Features::emailVerification(), ] ``` -------------------------------- ### Delete Eloquent Model Instance Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md To delete a specific model instance, retrieve it and then call the `delete` method on the instance. This will remove the corresponding record from the database. ```php use App\Models\Flight; $flight = Flight::find(1); $flight->delete(); ``` -------------------------------- ### Get PSR-7 Request Instance - PHP Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/requests.md Obtain a PSR-7 compatible request instance by type-hinting `Psr\Http\Message\ServerRequestInterface` on route closures or controller methods after installing `symfony/psr-http-message-bridge` and `nyholm/psr7`. ```php use Psr\Http\Message\ServerRequestInterface; Route::get('/', function (ServerRequestInterface $request) { // }); ``` -------------------------------- ### Install Laravel Cashier (Paddle) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/cashier-paddle.md Installs the Laravel Cashier package for Paddle integration using Composer. It's recommended to also set up webhook handling after installation. ```bash composer require laravel/cashier-paddle ``` -------------------------------- ### Clone Laravel Homestead Repository Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/homestead.md Clones the Laravel Homestead repository to the specified directory. This is the initial step for installing Homestead on your host machine. ```bash git clone https://github.com/laravel/homestead.git ~/Homestead ``` -------------------------------- ### Permanently Delete Soft Deleted Model Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This code demonstrates how to permanently remove a soft-deleted Eloquent model from the database using the `forceDelete` method. This action is irreversible. ```php $flight->forceDelete(); ``` ```php $flight->history()->forceDelete(); ``` -------------------------------- ### Publish Horizon Assets (Artisan) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/horizon.md Publishes Horizon's assets, including the configuration file, using the `horizon:install` Artisan command. This should be run after installing the package via Composer. ```bash php artisan horizon:install ``` -------------------------------- ### Install MeiliSearch PHP SDKs Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/scout.md These commands install the necessary MeiliSearch PHP SDK and HTTP factory implementations via Composer, required for using the MeiliSearch driver with Laravel Scout. ```bash composer require meilisearch/meilisearch-php http-interop/http-factory-guzzle ``` -------------------------------- ### Registering Event Listeners with Closures (PHP) Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md Shows how to register event listeners using closures directly within the model's `booted` method. This approach is useful for simple event handling without requiring separate event classes. It also demonstrates how to make these closures queueable for background processing. ```php where('airline_id', 1) ->get(); ``` -------------------------------- ### Make ChromeDriver Binaries Executable Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/dusk.md This command ensures that the ChromeDriver binaries downloaded by Dusk have the necessary execute permissions, which is crucial for Dusk to run tests. ```bash chmod -R 0755 vendor/laravel/dusk/bin/ ``` -------------------------------- ### Customize Eloquent Model Timestamp Column Names Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This snippet shows how to rename the columns Eloquent uses for 'created_at' and 'updated_at'. Define `CREATED_AT` and `UPDATED_AT` constants on the model. ```php 'local', 'root' => '/path/to/root', ]); $disk->put('image.jpg', $content); ``` -------------------------------- ### Disable Eloquent Model Timestamps Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This snippet shows how to disable Eloquent's automatic management of 'created_at' and 'updated_at' timestamps. Set the public `$timestamps` property to `false`. ```php orderBy('name') ->take(10) ->get(); ``` -------------------------------- ### Fetch Passport Scopes via Axios Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/passport.md Retrieves all defined scopes for a Laravel Passport application using an Axios GET request to the '/oauth/scopes' endpoint. Useful for displaying available scopes to users. ```javascript axios.get('/oauth/scopes') .then(response => { console.log(response.data); }); ``` -------------------------------- ### Installing Node and NPM Dependencies Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/mix.md These commands are used to check the installed versions of Node.js and NPM, and to install project dependencies defined in the `package.json` file. Node.js and NPM are prerequisites for running Laravel Mix. ```bash node -v npm -v ``` ```bash ./sail node -v ./sail npm -v ``` ```bash npm install ``` -------------------------------- ### Query Including Soft Deleted Models Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/eloquent.md This snippet shows how to include soft-deleted models in query results by using the `withTrashed` method. By default, soft-deleted models are excluded from queries. ```php use App\Models\Flight; $flights = Flight::withTrashed() ->where('account_id', 1) ->get(); ``` ```php $flight->history()->withTrashed()->get(); ``` -------------------------------- ### Install Passport and Generate Keys Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/passport.md Run the passport:install Artisan command to generate encryption keys for secure access tokens and create default clients for personal access and password grants. ```bash php artisan passport:install ``` -------------------------------- ### Install Laravel Dusk Composer Package Source: https://github.com/dhtmdgkr123/laravel-8-docs/blob/8.x/dusk.md This command installs the Laravel Dusk package as a development dependency for your project using Composer. ```bash composer require --dev laravel/dusk ```