### Install Laravel via Composer and Serve Source: https://laravel.com/docs/8.x/installation Install a new Laravel project using Composer and then start the local development server using the Artisan CLI. This method requires PHP and Composer to be installed. ```bash composer create-project laravel/laravel:^8.0 example-app cd example-app php artisan serve ``` -------------------------------- ### Initialize Dusk Tests Source: https://laravel.com/docs/8.x/dusk Run the dusk:install Artisan command to create the necessary directories and example test files for Dusk. ```bash php artisan dusk:install ``` -------------------------------- ### Install PHP with Homebrew Source: https://laravel.com/docs/8.x/valet Install PHP using Homebrew, a prerequisite for Valet. ```bash brew install php ``` -------------------------------- ### Install Laravel Telescope Source: https://laravel.com/docs/8.x/telescope Install Telescope using Composer and then run the Artisan commands to install assets and migrate the database. ```bash composer require laravel/telescope php artisan telescope:install php artisan migrate ``` -------------------------------- ### Run Breeze Installation and Compile Assets Source: https://laravel.com/docs/8.x/starter-kits Execute the Breeze installation command, install Node.js dependencies, compile assets, and run database migrations. ```bash php artisan breeze:install npm install npm run dev php artisan migrate ``` -------------------------------- ### GitHub Actions Configuration for Dusk Tests Source: https://laravel.com/docs/8.x/dusk This is a starting point for GitHub Actions to run Dusk tests. It includes checking out code, setting up the database, installing dependencies, and starting the Laravel server. ```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 ``` -------------------------------- ### Start Sail Development Environment Source: https://laravel.com/docs/8.x/sail Execute the sail script with the 'up' command to start the Docker containers for your development environment. This is the initial step after installation. ```bash ./vendor/bin/sail up ``` -------------------------------- ### Install Node.js and NPM Source: https://laravel.com/docs/8.x/mix Verify Node.js and NPM installations. If using Laravel Sail, invoke these commands through Sail. ```bash node -v npm -v ``` ```bash ./sail node -v ./sail npm -v ``` -------------------------------- ### Install Valet and Configure Services Source: https://laravel.com/docs/8.x/valet Run the Valet install command to configure Valet, DnsMasq, and set up services to launch on system startup. ```bash valet install ``` -------------------------------- ### Install Flysystem SFTP package Source: https://laravel.com/docs/8.x/filesystem Install the Flysystem package for SFTP support using Composer. ```bash composer require league/flysystem-sftp "~1.0" ``` -------------------------------- ### Install Passport and Generate Keys Source: https://laravel.com/docs/8.x/passport Execute the passport:install command to generate encryption keys for secure access tokens and create initial clients. ```bash php artisan passport:install ``` -------------------------------- ### Install Ably PHP SDK Source: https://laravel.com/docs/8.x/broadcasting Install the Ably PHP SDK using Composer. This is necessary for broadcasting events using Ably. ```bash composer require ably/ably-php ``` -------------------------------- ### Install Fortify with Composer Source: https://laravel.com/docs/8.x/fortify Use this command to install Laravel Fortify using the Composer package manager. ```bash composer require laravel/fortify ``` -------------------------------- ### Start Octane Server with File Watching Source: https://laravel.com/docs/8.x/octane Use the --watch flag to automatically restart the Octane server when application files change. Ensure Node.js and Chokidar are installed. ```bash php artisan octane:start --watch ``` -------------------------------- ### Install Laravel Breeze Source: https://laravel.com/docs/8.x/starter-kits Install the Laravel Breeze package using Composer. This command publishes authentication resources. ```bash composer require laravel/breeze:1.9.2 ``` -------------------------------- ### Start Homestead VM Source: https://laravel.com/docs/8.x/homestead Bring up the Homestead virtual machine after updating or making configuration changes. ```bash vagrant up ``` -------------------------------- ### start Source: https://laravel.com/docs/8.x/helpers Adds a single instance of the given value to a string if it does not already start with that value. ```APIDOC ## `start` ### Description Adds a single instance of the given value to a string if it does not already start with that value. ### Method Signature `start(string $value, string $start): string` ### Example ```php use Illuminate\Support\Str; $adjusted = Str::of('this/string')->start('/'); // /this/string $adjusted = Str::of('/this/string')->start('/'); // /this/string ``` ``` -------------------------------- ### Install Laravel Valet Source: https://laravel.com/docs/8.x/valet Install Valet globally using Composer after ensuring the Composer vendor bin directory is in your PATH. ```bash composer global require laravel/valet ``` -------------------------------- ### Start Laravel Sail Development Server Source: https://laravel.com/docs/8.x After creating the project, navigate to the project directory and start Laravel Sail. The first run will build the Docker containers, which may take some time. ```bash cd example-app ./vendor/bin/sail up ``` -------------------------------- ### Install Breeze with React Stack Source: https://laravel.com/docs/8.x/starter-kits Install Laravel Breeze with a React frontend stack. Ensure you compile assets and run database migrations. ```bash php artisan breeze:install react npm install npm run dev php artisan migrate ``` -------------------------------- ### Install Composer Dependencies for Existing Projects Source: https://laravel.com/docs/8.x/sail Use this command to install Composer dependencies for an existing project cloned from a repository. It utilizes a temporary Docker container with PHP and Composer to ensure consistent dependency installation. ```bash docker run --rm \ -u "$(id -u):$(id -g)" \ -v $(pwd):/var/www/html \ -w /var/www/html \ laravelsail/php81-composer:latest \ composer install --ignore-platform-reqs ``` -------------------------------- ### Start Laravel Sail Source: https://laravel.com/docs/8.x Navigate to your project directory and start Laravel Sail to build and run the application's Docker containers. The first run may take several minutes. ```bash cd example-app ./vendor/bin/sail up ``` -------------------------------- ### Switch PHP Versions Source: https://laravel.com/docs/8.x/valet Use the 'valet use' command to switch between installed PHP versions. Valet will install the specified version if it's not already present. ```bash valet use php@7.2 ``` ```bash valet use php ``` -------------------------------- ### Start Horizon Source: https://laravel.com/docs/8.x/horizon Start the Horizon process after configuring supervisors and workers in `config/horizon.php`. This command starts all configured worker processes for the current environment. ```bash php artisan horizon ``` -------------------------------- ### Install Chokidar File Watching Library Source: https://laravel.com/docs/8.x/octane Install the Chokidar library as a development dependency to enable file watching for the Octane server. ```bash npm install --save-dev chokidar ``` -------------------------------- ### Publish Horizon Assets Source: https://laravel.com/docs/8.x/horizon After installation, publish Horizon's assets using the `horizon:install` Artisan command. This sets up necessary files and configurations. ```bash php artisan horizon:install ``` -------------------------------- ### Install Swoole Extension Source: https://laravel.com/docs/8.x/octane If using the Swoole application server, install the Swoole PHP extension via PECL. ```bash pecl install swoole ``` -------------------------------- ### Install AWS SDK for PHP Source: https://laravel.com/docs/8.x/mail Install the AWS SDK for PHP using Composer to enable the SES mail driver. ```bash composer require aws/aws-sdk-php ``` -------------------------------- ### Setup PHP Code in Envoy Source: https://laravel.com/docs/8.x/envoy Use the @setup directive to define a block of PHP code that will execute before your Envoy tasks. ```php @setup $now = new DateTime; @endsetup ``` -------------------------------- ### Install Breeze with Vue Stack Source: https://laravel.com/docs/8.x/starter-kits Install Laravel Breeze with a Vue.js frontend stack. Remember to compile assets and migrate the database afterwards. ```bash php artisan breeze:install vue npm install npm run dev php artisan migrate ``` -------------------------------- ### Install Flysystem Cached Adapter package Source: https://laravel.com/docs/8.x/filesystem Install the Flysystem Cached Adapter package via Composer for improved performance. ```bash composer require league/flysystem-cached-adapter "~1.0" ``` -------------------------------- ### Local-Only Installation of Laravel Telescope Source: https://laravel.com/docs/8.x/telescope Install Telescope as a development dependency and conditionally register its service providers in AppServiceProvider for local development only. ```bash composer require laravel/telescope --dev php artisan telescope:install php artisan migrate ``` ```php app->environment('local')) { $this->app->register(\Laravel\Telescope\TelescopeServiceProvider::class); $this->app->register(TelescopeServiceProvider::class); } } } ``` ```json "extra": { "laravel": { "dont-discover": [ "laravel/telescope" ] } }, ``` -------------------------------- ### Create Browser Instance and Log In Source: https://laravel.com/docs/8.x/dusk Use the `browse` method to create a browser instance for testing. This example logs in a user and asserts the path after login. ```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 Algolia PHP SDK Source: https://laravel.com/docs/8.x/scout When using the Algolia driver, install the official Algolia PHP SDK via Composer. ```bash composer require algolia/algoliasearch-client-php ``` -------------------------------- ### Install SMS Notification Channel Packages Source: https://laravel.com/docs/8.x/notifications Install the necessary Composer packages for sending SMS notifications via Vonage. ```bash composer require laravel/nexmo-notification-channel nexmo/laravel ``` -------------------------------- ### Install Laravel Echo and Pusher JS Source: https://laravel.com/docs/8.x/broadcasting Install the necessary JavaScript packages for Laravel Echo and Pusher JS using NPM. This is a prerequisite for client-side broadcasting setup. ```bash npm install --save-dev laravel-echo pusher-js ``` -------------------------------- ### Parallel Testing Hooks Setup Source: https://laravel.com/docs/8.x/testing Implement setup and teardown logic for parallel test processes and test cases using the `ParallelTesting` facade. These hooks allow for resource preparation and cleanup. ```php whereStartsWith('wire:model') }} ``` -------------------------------- ### Install Breeze with API Stack Source: https://laravel.com/docs/8.x/starter-kits Install Laravel Breeze with an API stack, suitable for modern JavaScript applications. This sets up the `FRONTEND_URL` environment variable. ```bash php artisan breeze:install api php artisan migrate ``` -------------------------------- ### Install Slack Notification Channel Source: https://laravel.com/docs/8.x/notifications Install the Slack notification channel via Composer using the provided command. This is a prerequisite for sending notifications to Slack. ```bash composer require laravel/slack-notification-channel ``` -------------------------------- ### Execute Sail Commands with Alias Source: https://laravel.com/docs/8.x/sail Once the Bash alias is configured, you can execute Sail commands using the shorthand 'sail'. This example starts the development environment. ```bash sail up ``` -------------------------------- ### Get Every Nth Element from Collection Source: https://laravel.com/docs/8.x/collections The `nth` method creates a new collection containing every n-th element. An optional starting offset can be provided. ```php $collection = collect(['a', 'b', 'c', 'd', 'e', 'f']); $collection->nth(4); // ['a', 'e'] ``` ```php $collection->nth(4, 1); // ['b', 'f'] ``` -------------------------------- ### Retrieve All Rows From Users Table Source: https://laravel.com/docs/8.x/queries Use the DB facade's `table` method to start a query and the `get` method to retrieve all results as a Collection of stdClass objects. ```php get(); return view('user.index', ['users' => $users]); } } ``` ```php use Illuminate\Support\Facades\DB; $users = DB::table('users')->get(); foreach ($users as $user) { echo $user->name; } ``` -------------------------------- ### Initialize Homestead Configuration Source: https://laravel.com/docs/8.x/homestead Run the init script to create the Homestead.yaml configuration file. Use init.sh for macOS/Linux and init.bat for Windows. ```bash // macOS / Linux... bash init.sh ``` ```batch // Windows... init.bat ``` -------------------------------- ### Install MeiliSearch PHP SDKs Source: https://laravel.com/docs/8.x/scout When using the MeiliSearch driver, install the necessary PHP SDKs via Composer. Ensure compatibility with your MeiliSearch binary version. ```bash composer require meilisearch/meilisearch-php http-factory-guzzle/http-factory-guzzle ``` -------------------------------- ### Listen for Public Channel Events with Laravel Echo Source: https://laravel.com/docs/8.x/broadcasting Use the `channel` method to get a channel instance and `listen` to subscribe to events. Ensure Laravel Echo is installed and instantiated. ```javascript Echo.channel(`orders.${this.order.id}`) .listen('OrderShipmentStatusUpdated', (e) => { console.log(e.order.name); }); ``` -------------------------------- ### Create Subscription (No Payment Up Front) Source: https://laravel.com/docs/8.x/cashier-paddle After setting up a "generic" trial, create an actual subscription for the user using the `newSubscription` method as usual. Payment details will be collected at this stage if not already on file. ```php use Illuminate\Http\Request; Route::get('/user/subscribe', function (Request $request) { $payLink = $user->newSubscription('default', $monthly = 12345) ->returnTo(route('home')) ->create(); return view('billing', ['payLink' => $payLink]); }); ``` -------------------------------- ### Migrate Database Source: https://laravel.com/docs/8.x/fortify Run database migrations to set up the necessary tables for Fortify. ```bash php artisan migrate ``` -------------------------------- ### Install Laravel Octane Source: https://laravel.com/docs/8.x/octane Install Octane using Composer. After installation, run the octane:install Artisan command to publish Octane's configuration file. ```bash composer require laravel/octane ``` ```bash php artisan octane:install ``` -------------------------------- ### Create Subscription with Trial Days (Payment Up Front) Source: https://laravel.com/docs/8.x/cashier-paddle Use the `trialDays` method when creating a subscription pay link to offer trial periods while collecting payment method details upfront. This sets the trial end date and prevents billing until after the trial. ```php use Illuminate\Http\Request; Route::get('/user/subscribe', function (Request $request) { $payLink = $request->user()->newSubscription('default', $monthly = 12345) ->returnTo(route('home')) ->trialDays(10) ->create(); return view('billing', ['payLink' => $payLink]); }); ``` -------------------------------- ### Install Laravel Installer Globally Source: https://laravel.com/docs/8.x/installation Install the Laravel Installer as a global Composer dependency to easily create new Laravel projects. Ensure Composer's vendor bin directory is in your system's PATH. ```bash composer global require laravel/installer laravel new example-app cd example-app php artisan serve ``` -------------------------------- ### Update Homebrew Source: https://laravel.com/docs/8.x/valet Ensure Homebrew is up to date before installing Valet. ```bash brew update ``` -------------------------------- ### Install Laravel Homestead with Composer Source: https://laravel.com/docs/8.x/homestead Install Homestead into your project using Composer as a development dependency. This is part of the per-project installation method. ```bash composer require laravel/homestead --dev ``` -------------------------------- ### Install Pusher Channels SDK Source: https://laravel.com/docs/8.x/broadcasting Install the Pusher Channels PHP SDK using Composer. This is required if you plan to broadcast events using Pusher Channels. ```bash composer require pusher/pusher-php-server ``` -------------------------------- ### Configure FTP Filesystem Source: https://laravel.com/docs/8.x/filesystem Use this configuration to set up an FTP filesystem. Ensure FTP credentials are set in your environment variables. ```php 'ftp' => [ 'driver' => 'ftp', 'host' => env('FTP_HOST'), 'username' => env('FTP_USERNAME'), 'password' => env('FTP_PASSWORD'), // Optional FTP Settings... // 'port' => env('FTP_PORT', 21), // 'root' => env('FTP_ROOT'), // 'passive' => true, // 'ssl' => true, // 'timeout' => 30, ], ``` -------------------------------- ### Start Octane Server Source: https://laravel.com/docs/8.x/octane Use the octane:start Artisan command to run your Laravel application with Octane. By default, it starts on port 8000. ```bash php artisan octane:start ``` -------------------------------- ### LocalValetDriver Example Source: https://laravel.com/docs/8.x/valet Define a custom Valet driver for a single application by creating `LocalValetDriver.php` in the application's root. This example extends `LaravelValetDriver` and overrides the `serves` and `frontControllerPath` methods. ```php class LocalValetDriver extends LaravelValetDriver { /** * Determine if the driver serves the request. * * @param string $sitePath * @param string $siteName * @param string $uri * @return bool */ public function serves($sitePath, $siteName, $uri) { return true; } /** * Get the fully resolved path to the application's front controller. * * @param string $sitePath * @param string $siteName * @param string $uri * @return string */ public function frontControllerPath($sitePath, $siteName, $uri) { return $sitePath.'/public_html/index.php'; } } ``` -------------------------------- ### Using Cache and Route Facades Source: https://laravel.com/docs/8.x/facades Demonstrates how to use the Cache and Route facades to define a route that retrieves a value from the cache. ```php use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Route; Route::get('/cache', function () { return Cache::get('key'); }); ``` -------------------------------- ### Basic Asset Compilation with Mix Source: https://laravel.com/docs/8.x/mix This example shows a basic Mix configuration for compiling JavaScript and PostCSS. Ensure your webpack.mix.js file is correctly set up. ```javascript mix.js('resources/js/app.js', 'public/js') .postCss('resources/css/app.css', 'public/css'); ``` -------------------------------- ### Create Subscription with Coupon Source: https://laravel.com/docs/8.x/cashier-paddle Apply a coupon when creating a subscription by using the `withCoupon` method before calling `create`. ```PHP $payLink = $user->newSubscription('default', $monthly = 12345) ->returnTo(route('home')) ->withCoupon('code') ->create(); ``` -------------------------------- ### Install Laravel Tinker Source: https://laravel.com/docs/8.x/artisan Install Tinker using Composer if it has been removed from your application. ```bash composer require laravel/tinker ``` -------------------------------- ### Install Guzzle HTTP Client Source: https://laravel.com/docs/8.x/http-client Ensure Guzzle is installed as a dependency using Composer. ```bash composer require guzzlehttp/guzzle ``` -------------------------------- ### Testing Helper Functions with Facade Mocking Source: https://laravel.com/docs/8.x/facades Demonstrates how to test helper functions by mocking the underlying facade. This approach allows verification of method calls on the facade's implementation. ```php use Illuminate\Support\Facades\Cache; /** * A basic functional test example. * * @return void */ public function testBasicExample() { Cache::shouldReceive('get') ->with('key') ->andReturn('value'); $response = $this->get('/cache'); $response->assertSee('value'); } ``` -------------------------------- ### Podcast Model Without Real-Time Facades Source: https://laravel.com/docs/8.x/facades This example shows a `Podcast` model that requires explicit injection of a `Publisher` instance. This approach allows for easy testing by mocking the injected publisher, but necessitates passing an instance every time the `publish` method is called. ```php update(['publishing' => now()]); $publisher->publish($this); } } ``` -------------------------------- ### whenStartsWith Source: https://laravel.com/docs/8.x/helpers Invokes a closure if the string starts with the given sub-string. The closure receives the fluent string instance. ```APIDOC ## `whenStartsWith` ### Description Invokes the given closure if the string starts with the given sub-string. The closure will receive the fluent string instance. ### Method Signature `whenStartsWith(string|array $prefixes, callable $callback, ?callable $otherwise = null): static|"TValue"|"TClosureReturn" ### Parameters #### `$prefixes` (string|array) - Required - The prefix or array of prefixes to check for at the beginning of the string. #### `$callback` (callable) - Required - The closure to execute if the string starts with any of the `$prefixes`. #### `$otherwise` (callable | null) - Optional - The closure to execute if the string does not start with any of the `$prefixes`. ### Example ```php use Illuminate\Support\Str; $string = Str::of('disney world')->whenStartsWith('disney', function ($string) { return $string->title(); }); // 'Disney World' ``` ``` -------------------------------- ### Share Site via Expose Source: https://laravel.com/docs/8.x/valet Share your local Valet site publicly using Expose. Navigate to the site's directory and run the expose command. Press Control + C to stop sharing. ```bash cd ~/Sites/laravel expose ``` -------------------------------- ### Install Laravel Scout Source: https://laravel.com/docs/8.x/scout Install Scout using Composer. This command adds the Scout package to your project. ```bash composer require laravel/scout ``` -------------------------------- ### Install Laravel Sanctum Source: https://laravel.com/docs/8.x/sanctum Install Sanctum using Composer. This command adds the package to your project dependencies. ```bash composer require laravel/sanctum ``` -------------------------------- ### Create Controller for Post Management Source: https://laravel.com/docs/8.x/validation Set up a controller with methods to display the post creation form and handle the storage of new posts. ```php with('key') ->andReturn('value'); $response = $this->get('/cache'); $response->assertSee('value'); } ``` -------------------------------- ### Get All Directories in a Directory Source: https://laravel.com/docs/8.x/filesystem Use the `directories` method to get an array of all directories within a specified directory. ```php $directories = Storage::directories($directory); ``` -------------------------------- ### Create New Laravel Project Source: https://laravel.com/docs/8.x Run this command in your terminal to create a new Laravel application directory. Replace 'example-app' with your desired project name. ```bash curl -s "https://laravel.build/example-app" | bash ``` -------------------------------- ### Add Prefix to String Source: https://laravel.com/docs/8.x/helpers The `start` method ensures a string begins with a specific value, adding it only if it's missing. ```php use Illuminate\Support\Str; $adjusted = Str::of('this/string')->start('/'); // /this/string $adjusted = Str::of('/this/string')->start('/'); // /this/string ``` -------------------------------- ### Install Laravel Horizon Source: https://laravel.com/docs/8.x/horizon Install Horizon using Composer. This command adds the Horizon package to your project dependencies. ```bash composer require laravel/horizon ``` -------------------------------- ### make() Source: https://laravel.com/docs/8.x/collections Creates a new collection instance. ```APIDOC ## make() ### Description Creates a new collection instance. See the [Creating Collections](#creating-collections) section. ### Method `make(mixed $items = null)` ### Parameters - **$items** (mixed) - The items to create the collection from. ### Request Example ```php use Illuminate\Support\Collection; $collection = Collection::make([1, 2, 3]); ``` ``` -------------------------------- ### Disable Automatic ChromeDriver Start Source: https://laravel.com/docs/8.x/dusk Comment out the `startChromeDriver` method in `tests/DuskTestCase.php` to prevent Dusk from automatically starting ChromeDriver. ```php /** * Prepare for Dusk test execution. * * @beforeClass * @return void */ public static function prepare() { // static::startChromeDriver(); } ``` -------------------------------- ### Publish Fortify Resources Source: https://laravel.com/docs/8.x/fortify After installation, publish Fortify's resources including actions, configuration, and migrations using the vendor:publish Artisan command. ```bash php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider" ``` -------------------------------- ### Create Subscription with Trial Until Date Source: https://laravel.com/docs/8.x/billing Use `trialUntil` with a `DateTime` instance to specify the exact end of the trial period. Ensure the payment method is provided. ```PHP use Carbon\Carbon; $user->newSubscription('default', 'price_monthly') ->trialUntil(Carbon::now()->addDays(10)) ->create($paymentMethod); ``` -------------------------------- ### Install Passport Package Source: https://laravel.com/docs/8.x/passport Install the Passport package using Composer. This is the first step in integrating Passport into your Laravel application. ```bash composer require laravel/passport ``` -------------------------------- ### Generate Vagrantfile and Homestead.yaml Source: https://laravel.com/docs/8.x/homestead After installing Homestead per project, use the 'make' command to generate the Vagrantfile and Homestead.yaml. These files will be placed in your project's root and automatically configure sites and folders. ```bash // macOS / Linux... php vendor/bin/homestead make ``` ```bash // Windows... vendor\bin\homestead make ``` -------------------------------- ### Install Laravel Dusk Source: https://laravel.com/docs/8.x/dusk Install the Laravel Dusk Composer dependency to add browser automation and testing capabilities to your project. ```bash composer require --dev laravel/dusk ``` -------------------------------- ### Set and List Redis values Source: https://laravel.com/docs/8.x/redis Demonstrates setting a string value with `Redis::set` and retrieving a range of elements from a list with `Redis::lrange`. Ensure the Redis connection is configured. ```PHP use Illuminate\Support\Facades\Redis; Redis::set('name', 'Taylor'); $values = Redis::lrange('names', 5, 10); ``` -------------------------------- ### Basic Controller Example Source: https://laravel.com/docs/8.x/controllers Define a basic controller extending the base controller class to handle specific requests. Ensure routes are defined to point to controller methods. ```php User::findOrFail($id) ]); } } ``` ```php use App\Http\Controllers\UserController; Route::get('/user/{id}', [UserController::class, 'show']); ``` -------------------------------- ### Define Basic GET Route Source: https://laravel.com/docs/8.x/routing Register a simple route that responds to GET requests with a specific URI and executes a closure. ```PHP use Illuminate\Support\Facades\Route; Route::get('/greeting', function () { return 'Hello World'; }); ``` -------------------------------- ### Str::start() Source: https://laravel.com/docs/8.x/helpers Adds a single instance of a given value to the beginning of a string if it doesn't already start with it. ```APIDOC ## Str::start() ### Description Adds a single instance of the given value to a string if it does not already start with that value. ### Method `Str::start(string $value, string $prefix)` ### Parameters #### Path Parameters - **value** (string) - The string to adjust. - **prefix** (string) - The prefix to ensure the string starts with. ### Request Example ```php use Illuminate\Support\Str; $adjusted = Str::start('this/string', '/'); // '/this/string' $adjusted = Str::start('/this/string', '/'); // '/this/string' ``` ``` -------------------------------- ### get() Source: https://laravel.com/docs/8.x/collections The `get` method returns the item at a given key. It can also accept a default value or a callback for missing keys. ```APIDOC ## get() ### Description Retrieves an item from the collection by its key. Returns `null` or a default value if the key is not found. ### Method `get(key, defaultValue = null)` ### Parameters #### Path Parameters - **key** (string) - The key of the item to retrieve. - **defaultValue** (mixed, optional) - The default value to return if the key does not exist. Can be a value or a callback. ### Request Example ```php $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); // Get existing key $value = $collection->get('name'); // Get non-existent key with default value $value = $collection->get('age', 34); // Get non-existent key with default callback $value = $collection->get('email', function () { return 'taylor@example.com'; }); ``` ### Response #### Success Response (mixed) - Returns the value associated with the key, or the default value/callback result if the key is not found. ### Response Example ```php // For $value = $collection->get('name'); // taylor // For $value = $collection->get('age', 34); // 34 // For $value = $collection->get('email', function () { ... }); // taylor@example.com ``` ``` -------------------------------- ### Drop All Tables, Migrate, and Seed Source: https://laravel.com/docs/8.x/migrations Drops all database tables, runs all migrations, and then seeds the database using `migrate:fresh --seed`. ```bash php artisan migrate:fresh --seed ``` -------------------------------- ### List Available Artisan Make Commands Source: https://laravel.com/docs/8.x/structure View all available Artisan commands for generating classes and other application components. ```bash php artisan list make ``` -------------------------------- ### Create Laravel Project with Git Initialization Source: https://laravel.com/docs/8.x Use the --git flag to automatically initialize a Git repository and commit the base Laravel skeleton when creating a new project. ```bash laravel new example-app --git ``` -------------------------------- ### Create New Laravel Application Source: https://laravel.com/docs/8.x/starter-kits Use this command to create a new Laravel application and set up the initial project structure. ```bash curl -s https://laravel.build/example-app | bash cd example-app php artisan migrate ``` -------------------------------- ### Create Subscription with Trial Days Up Front Source: https://laravel.com/docs/8.x/billing Use `trialDays` when creating a subscription to collect payment information upfront and set a trial period. Cashier will override any Stripe price trial defaults. ```PHP use Illuminate\Http\Request; Route::post('/user/subscribe', function (Request $request) { $request->user()->newSubscription('default', 'price_monthly') ->trialDays(10) ->create($request->paymentMethodId); // ... }); ``` -------------------------------- ### Check if String Starts With Value Source: https://laravel.com/docs/8.x/helpers Determines if a string begins with a specific value. It can also check against an array of possible starting values. ```php use Illuminate\Support\Str; $result = Str::startsWith('This is my name', 'This'); ``` ```php $result = Str::startsWith('This is my name', ['This', 'That', 'There']); ``` -------------------------------- ### Ensure String Starts With Value Source: https://laravel.com/docs/8.x/helpers Adds a specified prefix to a string only if it doesn't already start with it. This ensures consistent string beginnings. ```php use Illuminate\Support\Str; $adjusted = Str::start('this/string', '/'); ``` ```php $adjusted = Str::start('/this/string', '/'); ``` -------------------------------- ### Using Response Facade vs. Response Helper Source: https://laravel.com/docs/8.x/facades Compares using the Response facade to generate a JSON response with using the global `response` helper function. Helper functions are globally available and do not require imports. ```php use Illuminate\Support\Facades\Response; Route::get('/users', function () { return Response::json([ // ... ]); }); ``` ```php Route::get('/users', function () { return response()->json([ // ... ]); }); ``` -------------------------------- ### Get a Redis value Source: https://laravel.com/docs/8.x/redis Use the `Redis` facade to call the `GET` command. This is useful for retrieving cached data or session information. ```PHP Redis::get('user:profile:'.$id) ]); } } ``` -------------------------------- ### Configure Dusk Environment File Source: https://laravel.com/docs/8.x/dusk Create a `.env.dusk.{environment}` file (e.g., `.env.dusk.local`) to specify a custom environment file for Dusk tests. Dusk will back up and restore your main `.env` file during test execution. ```bash # Example: .env.dusk.local ``` -------------------------------- ### Laravel PHPDoc Block Example Source: https://laravel.com/docs/8.x/contributions Example of a valid PHPDoc block in Laravel. Note the specific spacing around the `@param` attribute. ```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) { // } ``` -------------------------------- ### Generate a Service Provider with Artisan Source: https://laravel.com/docs/8.x/providers Use the `make:provider` Artisan command to generate a new service provider class. ```bash php artisan make:provider RiakServiceProvider ``` -------------------------------- ### Create Response Instance with `response()` Source: https://laravel.com/docs/8.x/helpers Creates a response instance or obtains an instance of the response factory for generating various types of responses. ```PHP return response('Hello World', 200, $headers); ``` ```PHP return response()->json(['foo' => 'bar'], 200, $headers); ``` -------------------------------- ### Install Legacy Model Factories Source: https://laravel.com/docs/8.x/upgrade To continue using Laravel 7.x style model factories in Laravel 8.x, install the `laravel/legacy-factories` package. ```bash composer require laravel/legacy-factories ``` -------------------------------- ### Configure Horizon Environments Source: https://laravel.com/docs/8.x/horizon Define worker process options for different environments in `config/horizon.php`. This example shows configurations for 'production' and 'local' environments, including max processes and balancing settings. ```php 'environments' => [ 'production' => [ 'supervisor-1' => [ 'maxProcesses' => 10, 'balanceMaxShift' => 1, 'balanceCooldown' => 3, ], ], 'local' => [ 'supervisor-1' => [ 'maxProcesses' => 3, ], ], ], ``` -------------------------------- ### Create On-Demand Disk Source: https://laravel.com/docs/8.x/filesystem Build a disk at runtime with a given configuration array using the Storage facade's 'build' method, without needing it in the 'filesystems' configuration file. ```php use Illuminate\Support\Facades\Storage; $disk = Storage::build([ 'driver' => 'local', 'root' => '/path/to/root', ]); $disk->put('image.jpg', $content); ``` -------------------------------- ### Enter Tinker REPL Environment Source: https://laravel.com/docs/8.x/artisan Start the Tinker REPL to interact with your Laravel application on the command line. ```bash php artisan tinker ``` -------------------------------- ### Install Supervisor Source: https://laravel.com/docs/8.x/horizon Install Supervisor, a process monitor for Linux, which automatically restarts the `horizon` process if it stops unexpectedly. This command is for Ubuntu systems. ```bash sudo apt-get install supervisor ``` -------------------------------- ### Controller Using Cache Facade Source: https://laravel.com/docs/8.x/facades A controller example demonstrating the use of the Cache facade to retrieve data. Facades provide a convenient, static-like interface to container-bound services. ```php $user]); } } ``` -------------------------------- ### Extract Substring Source: https://laravel.com/docs/8.x/helpers Returns a portion of a string based on a starting position and length. Ensure the start and length parameters are within the string bounds. ```php use Illuminate\Support\Str; $converted = Str::substr('The Laravel Framework', 4, 7); ``` -------------------------------- ### Start Laravel Tinker Session Source: https://laravel.com/docs/8.x/sail Execute the 'sail tinker' command to start a new Laravel Tinker session for interactive code execution. ```bash sail tinker ``` -------------------------------- ### Create Subscription with Additional Details Source: https://laravel.com/docs/8.x/cashier-paddle Pass an array of key-value pairs to the `create` method to specify additional customer or subscription details, such as VAT numbers. ```PHP $payLink = $user->newSubscription('default', $monthly = 12345) ->returnTo(route('home')) ->create([ 'vat_number' => $vatNumber, ]); ```