### Install Valet Source: https://laravel.com/framework/docs/8.x/valet Configures and installs Valet and DnsMasq, and sets up daemons to launch on system start. ```bash valet install ``` -------------------------------- ### Run dusk:install Artisan Command Source: https://laravel.com/framework/docs/8.x/dusk Creates the tests/Browser directory and an example Dusk test. Run after installing the package. ```bash php artisan dusk:install ``` -------------------------------- ### Install Laravel via Composer and start server Source: https://laravel.com/framework/docs/8.x Create a new Laravel project using Composer, then start the local development server with `php artisan serve`. ```bash composer create-project laravel/laravel:^8.0 example-app cd example-app php artisan serve ``` -------------------------------- ### Install Laravel via Laravel Installer Source: https://laravel.com/framework/docs/8.x Install the Laravel Installer globally, then create a new project and start the server. Ensure Composer's vendor bin directory is in your $PATH. ```bash composer global require laravel/installer laravel new example-app cd example-app php artisan serve ``` -------------------------------- ### Start Sail with vendor/bin/sail up Source: https://laravel.com/framework/docs/8.x/sail Start Sail using the vendor/bin/sail script. This is the default way to invoke Sail commands. ```bash ./vendor/bin/sail up ``` -------------------------------- ### Install Telescope for local development only Source: https://laravel.com/framework/docs/8.x/telescope Install Telescope with the --dev flag, then publish assets and run migrations for local-only usage. ```bash composer require laravel/telescope --dev ``` ```bash php artisan telescope:install ``` ```bash php artisan migrate ``` -------------------------------- ### Install PHP via Homebrew Source: https://laravel.com/framework/docs/8.x/valet Installs PHP using Homebrew. ```bash brew install php ``` -------------------------------- ### Install Breeze with API stack Source: https://laravel.com/framework/docs/8.x/starter-kits Commands to install Breeze's authentication API stack for modern JavaScript applications, then run migrations. ```bash php artisan breeze:install api php artisan migrate ``` -------------------------------- ### Start Octane with --watch flag Source: https://laravel.com/framework/docs/8.x/octane Starts Octane with file watching to automatically restart on file changes. Requires Node and the Chokidar library installed. ```bash php artisan octane:start --watch ``` -------------------------------- ### Install Fortify via Composer Source: https://laravel.com/framework/docs/8.x/fortify Run this command to install Laravel Fortify using Composer. ```bash composer require laravel/fortify ``` -------------------------------- ### Install Swoole via PECL Source: https://laravel.com/framework/docs/8.x/octane Install the Swoole PHP extension using PECL. ```bash pecl install swoole ``` -------------------------------- ### GitHub Actions workflow for Laravel Dusk tests Source: https://laravel.com/framework/docs/8.x/dusk Use this GitHub Actions configuration to run Dusk tests on push events. It sets up the environment, starts MySQL, creates a database, installs Composer dependencies, generates an application key, upgrades Chrome Driver, starts the driver and Laravel server, runs Dusk tests, and uploads screenshots and 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 ``` -------------------------------- ### Start Laravel Sail Source: https://laravel.com/framework/docs/8.x Navigate to the application directory and run the Sail 'up' command to start the Docker containers. The first run builds the containers and may take several minutes; subsequent starts are faster. After starting, access the app at http://localhost. ```bash cd example-app ./vendor/bin/sail up ``` -------------------------------- ### Install Supervisor on Ubuntu Source: https://laravel.com/framework/docs/8.x/queues Use this command to install Supervisor on Ubuntu. It will automatically restart queue:work processes if they fail. ```bash sudo apt-get install supervisor ``` -------------------------------- ### unique() method example Source: https://laravel.com/framework/docs/8.x/collections Shows how to use the unique method to get unique items and reset keys with values(). The output is [1, 2, 3, 4]. ```php $collection = collect([1, 1, 2, 2, 3, 4, 2]); $unique = $collection->unique(); $unique->values()->all(); // [1, 2, 3, 4] ``` -------------------------------- ### get() returns item at a key Source: https://laravel.com/framework/docs/8.x/collections Returns the item at a given key. If the key does not exist, null is returned. The example retrieves the value for 'name'. ```php $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $value = $collection->get('name'); // taylor ``` -------------------------------- ### get() with callback default Source: https://laravel.com/framework/docs/8.x/collections Returns the item at a given key, or the result of a callback if the key does not exist. The example passes a callback that returns an email address. ```php $collection->get('email', function () { return '[email protected]'; }); // [email protected] ``` -------------------------------- ### Install Ably PHP SDK Source: https://laravel.com/framework/docs/8.x/broadcasting Install the Ably PHP SDK using Composer. This is required to broadcast events via Ably. ```bash composer require ably/ably-php ``` -------------------------------- ### nth() - get every n-th element with starting offset Source: https://laravel.com/framework/docs/8.x/collections Creates a new collection consisting of every n-th element, starting from a given offset. Example shows usage with offset as second argument. ```php $collection->nth(4, 1); // ['b', 'f'] ``` -------------------------------- ### reduce: Specify initial carry value Source: https://laravel.com/framework/docs/8.x/collections Passing a second argument to reduce sets the initial value of $carry. The example starts with 4 and sums [1, 2, 3] to get 10. ```php $collection->reduce(function ($carry, $item) { return $carry + $item; }, 4); // 10 ``` -------------------------------- ### Str::substr() usage example Source: https://laravel.com/framework/docs/8.x/helpers Returns the portion of string specified by the start and length parameters. The example extracts 'Laravel' from 'The Laravel Framework' starting at position 4 with length 7. ```php use Illuminate\Support\Str; $converted = Str::substr('The Laravel Framework', 4, 7); // Laravel ``` -------------------------------- ### Start Supervisor with supervisorctl Source: https://laravel.com/framework/docs/8.x/horizon Updates Supervisor configuration and starts the monitored processes. Run these commands after creating the configuration file. ```bash sudo supervisorctl reread ``` ```bash sudo supervisorctl update ``` ```bash sudo supervisorctl start horizon ``` -------------------------------- ### Basic GET route with closure Source: https://laravel.com/framework/docs/8.x/routing Defines a route that responds to GET requests at /greeting and returns 'Hello World'. Uses the Route facade and a closure. ```php use Illuminate\Support\Facades\Route; Route::get('/greeting', function () { return 'Hello World'; }); ``` -------------------------------- ### Generate model with various class types using make:model options Source: https://laravel.com/framework/docs/8.x/eloquent Shows how to generate a model along with factories, seeders, controllers, policies, and more using various options. Includes shortcuts like -f, -s, -c, -crR, -mfsc, --all, and --pivot. ```bash # Generate a model and a FlightFactory class... php artisan make:model Flight --factory php artisan make:model Flight -f # Generate a model and a FlightSeeder class... php artisan make:model Flight --seed php artisan make:model Flight -s # Generate a model and a FlightController class... php artisan make:model Flight --controller php artisan make:model Flight -c # Generate a model, FlightController resource class, and form request classes... php artisan make:model Flight --controller --resource --requests php artisan make:model Flight -crR # Generate a model and a FlightPolicy class... php artisan make:model Flight --policy # Generate a model and a migration, factory, seeder, and controller... php artisan make:model Flight -mfsc # Shortcut to generate a model, migration, factory, seeder, policy, controller, and form requests... php artisan make:model Flight --all # Generate a pivot model... php artisan make:model Member --pivot ``` -------------------------------- ### slice() - Return a slice starting at index Source: https://laravel.com/framework/docs/8.x/collections Returns a slice of the collection starting at the given index. The example slices from index 4. ```php $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $slice = $collection->slice(4); $slice->all(); // [5, 6, 7, 8, 9, 10] ``` -------------------------------- ### Run breeze:install and compile assets Source: https://laravel.com/framework/docs/8.x/starter-kits Commands to publish Breeze's authentication views, routes, controllers, and other resources, then compile assets and run migrations. ```bash php artisan breeze:install npm install npm run dev php artisan migrate ``` -------------------------------- ### Start Supervisor Processes Source: https://laravel.com/framework/docs/8.x/queues Run these commands to update Supervisor configuration and start the laravel-worker processes. The start command targets all worker processes defined in the configuration. ```bash sudo supervisorctl reread sudo supervisorctl update sudo supervisorctl start laravel-worker:* ``` -------------------------------- ### start: Prepend value if not already present with Str::of()->start() Source: https://laravel.com/framework/docs/8.x/helpers Adds a single instance of the given value to a string if it does not already start with that value. Examples show adding a slash to a string that doesn't start with it and leaving one that does unchanged. ```php use Illuminate\Support\Str; $adjusted = Str::of('this/string')->start('/'); // /this/string $adjusted = Str::of('/this/string')->start('/'); // /this/string ``` -------------------------------- ### Str::start() usage example Source: https://laravel.com/framework/docs/8.x/helpers Adds a single instance of the given value to a string if it does not already start with that value. The example adds '/' to 'this/string' but not to '/this/string'. ```php use Illuminate\Support\Str; $adjusted = Str::start('this/string', '/'); // /this/string $adjusted = Str::start('/this/string', '/'); // /this/string ``` -------------------------------- ### Create a resource controller with --resource option Source: https://laravel.com/framework/docs/8.x/controllers Run the Artisan command to generate a controller at app/Http/Controllers/PhotoController.php with methods for each resource operation. ```bash php artisan make:controller PhotoController --resource ``` -------------------------------- ### Run Envoy binary Source: https://laravel.com/framework/docs/8.x/envoy After installation, the Envoy binary is available in vendor/bin. Run this command to execute Envoy. ```bash php vendor/bin/envoy ``` -------------------------------- ### Create a browser instance with browse method Source: https://laravel.com/framework/docs/8.x/dusk Shows a basic Dusk test that creates a user, visits the login page, fills credentials, and asserts the path. The browse method passes a browser instance to the closure. ```php create([ 'email' => '[email protected]', ]); $this->browse(function ($browser) use ($user) { $browser->visit('/login') ->type('email', $user->email) ->type('password', 'password') ->press('Login') ->assertPathIs('/home'); }); } } ``` -------------------------------- ### startsWith: Check if string starts with given value with Str::of()->startsWith() Source: https://laravel.com/framework/docs/8.x/helpers Determines if the given string begins with the given value. The example returns true for 'This is my name' starting with 'This'. ```php use Illuminate\Support\Str; $result = Str::of('This is my name')->startsWith('This'); // true ``` -------------------------------- ### Update NODE_VERSION in docker-compose.yml Source: https://laravel.com/framework/docs/8.x/sail Modify the build.args of the laravel.test service in docker-compose.yml to change the Node version installed by Sail. Sail installs Node 16 by default; this example sets NODE_VERSION to '14'. ```yaml build: args: WWWGROUP: '${WWWGROUP}' NODE_VERSION: '14' ``` -------------------------------- ### Publish Telescope assets and run migrations Source: https://laravel.com/framework/docs/8.x/telescope After installing Telescope, publish its assets using the telescope:install Artisan command and run the migrate command to create the necessary tables. ```bash php artisan telescope:install ``` ```bash php artisan migrate ``` -------------------------------- ### Install Horizon via Composer Source: https://laravel.com/framework/docs/8.x/horizon Run this command to install Laravel Horizon using Composer. Requires Redis to be set as the queue connection in config/queue.php. ```bash composer require laravel/horizon ``` -------------------------------- ### Make a GET request with Http facade Source: https://laravel.com/framework/docs/8.x/http-client Use the Http facade's get method to make a basic GET request. Returns an Illuminate\Http\Client\Response instance. ```php use Illuminate\Support\Facades\Http; $response = Http::get('http://example.com'); ``` -------------------------------- ### Create on-demand disk with Storage::build Source: https://laravel.com/framework/docs/8.x/filesystem Create a disk at runtime by passing a configuration array to the Storage facade's build method. The configuration must include a driver and root path. The returned disk instance can then be used to store files. ```php use Illuminate\Support\Facades\Storage; $disk = Storage::build([ 'driver' => 'local', 'root' => '/path/to/root', ]); $disk->put('image.jpg', $content); ``` -------------------------------- ### diff method: get models not in given collection Source: https://laravel.com/framework/docs/8.x/eloquent-collections The diff method returns all models that are not present in the given collection. The example uses a query to get a collection of users with IDs 1, 2, and 3. ```php use App\Models\User; $users = $users->diff(User::whereIn('id', [1, 2, 3])->get()); ``` -------------------------------- ### Start Horizon with artisan horizon Source: https://laravel.com/framework/docs/8.x/horizon Starts all configured worker processes for the current environment. Run this command from your application's root directory. ```bash php artisan horizon ``` -------------------------------- ### Str::length() - Get string length Source: https://laravel.com/framework/docs/8.x/helpers Returns the length of the given string. Example output: 7. ```php use Illuminate\Support\Str; $length = Str::length('Laravel'); // 7 ``` -------------------------------- ### Create a Setup Intent with Cashier's createSetupIntent method Source: https://laravel.com/framework/docs/8.x/billing Use the Billable trait's createSetupIntent method in a route or controller to create a new Setup Intent and pass it to the view that renders the payment method form. ```php return view('update-payment-method', [ 'intent' => $user->createSetupIntent() ]); ``` -------------------------------- ### Retrieve options with option and options methods Source: https://laravel.com/framework/docs/8.x/artisan Use $this->option('queue') to get a specific option and $this->options() to get all options as an array. ```php // Retrieve a specific option... $queueName = $this->option('queue'); // Retrieve all options as an array... $options = $this->options(); ``` -------------------------------- ### Create a new Laravel project on Windows Source: https://laravel.com/framework/docs/8.x Run this command in a WSL2 terminal to create a new Laravel application in a directory named 'example-app'. The directory will be created in the current working directory. ```bash curl -s https://laravel.build/example-app | bash ``` -------------------------------- ### Access Swoole table with Octane::table Source: https://laravel.com/framework/docs/8.x/octane Uses the Octane facade to set and get values from the 'example' table. The set method stores a row with a UUID key, and the get method retrieves it. Requires Swoole. ```php use Laravel\Octane\Facades\Octane; Octane::table('example')->set('uuid', [ 'name' => 'Nuno Maduro', 'votes' => 1000, ]); return Octane::table('example')->get('uuid'); ``` -------------------------------- ### splice() basic example Source: https://laravel.com/framework/docs/8.x/collections Removes and returns a slice of items starting at the specified index. The original collection is modified. ```php $collection = collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2); $chunk->all(); // [3, 4, 5] $collection->all(); // [1, 2] ``` -------------------------------- ### Str::plural() example Source: https://laravel.com/framework/docs/8.x/helpers Converts a singular word to its plural form. Supports only English. The first example shows basic pluralization, the second shows using an integer second argument to get singular or plural form. ```php use Illuminate\Support\Str; $plural = Str::plural('car'); // cars $plural = Str::plural('child'); // children ``` ```php use Illuminate\Support\Str; $plural = Str::plural('child', 2); // children $singular = Str::plural('child', 1); // child ``` -------------------------------- ### View help screen for a command Source: https://laravel.com/framework/docs/8.x/artisan Precede the command name with `help` to display its arguments and options. ```bash php artisan help migrate ``` -------------------------------- ### Install Dropbox Flysystem Adapter with Composer Source: https://laravel.com/framework/docs/8.x/filesystem Install the community-maintained Dropbox adapter for Flysystem using Composer. This is required before registering the custom driver. ```bash composer require spatie/flysystem-dropbox ``` -------------------------------- ### Install Composer packages for S3, SFTP, and cached adapter Source: https://laravel.com/framework/docs/8.x/filesystem Run these Composer commands to install the required Flysystem packages for S3, SFTP, and optional cached adapter. ```bash composer require --with-all-dependencies league/flysystem-aws-s3-v3 "^1.0" ``` ```bash composer require league/flysystem-sftp "~1.0" ``` ```bash composer require league/flysystem-cached-adapter "~1.0" ``` -------------------------------- ### Build a query with constraints using Flight::where()->orderBy()->take()->get() Source: https://laravel.com/framework/docs/8.x/eloquent Add constraints to an Eloquent query and retrieve results with the get method. The example filters by active, orders by name, and limits to 10 results. ```php $flights = Flight::where('active', 1) ->orderBy('name') ->take(10) ->get(); ``` -------------------------------- ### Create an on-demand channel with Log::build Source: https://laravel.com/framework/docs/8.x/logging Create an on-demand channel by providing configuration at runtime without it being present in the logging configuration file. The example builds a 'single' driver channel with a custom log path and logs an info message. ```php use Illuminate\Support\Facades\Log; Log::build([ 'driver' => 'single', 'path' => storage_path('logs/custom.log'), ])->info('Something happened!'); ``` -------------------------------- ### intersect method: get models also present in given collection Source: https://laravel.com/framework/docs/8.x/eloquent-collections The intersect method returns all models that are also present in the given collection. The example uses a query to get a collection of users with IDs 1, 2, and 3. ```php use App\Models\User; $users = $users->intersect(User::whereIn('id', [1, 2, 3])->get()); ``` -------------------------------- ### kebab method example Source: https://laravel.com/framework/docs/8.x/helpers Converts a string to kebab-case. Example: 'fooBar' becomes 'foo-bar'. ```php use Illuminate\Support\Str; $converted = Str::of('fooBar')->kebab(); // foo-bar ``` -------------------------------- ### Install Laravel Valet via Composer Source: https://laravel.com/framework/docs/8.x/valet Installs Laravel Valet as a global Composer package. ```bash composer global require laravel/valet ``` -------------------------------- ### Run Homestead initialization script Source: https://laravel.com/framework/docs/8.x/homestead Executes the initialization script to create the Homestead.yaml configuration file. Use 'bash init.sh' on macOS/Linux and 'init.bat' on Windows. ```bash // macOS / Linux... bash init.sh // Windows... init.bat ``` -------------------------------- ### Accessing Tagged Cache Items with Cache::tags()->get() Source: https://laravel.com/framework/docs/8.x/cache Retrieve tagged cache items by passing the same ordered list of tags to tags() and then calling get() with the key. The example retrieves John and Anne using their respective tags. ```php $john = Cache::tags(['people', 'artists'])->get('John'); $anne = Cache::tags(['people', 'authors'])->get('Anne'); ``` -------------------------------- ### Str::pluralStudly() example Source: https://laravel.com/framework/docs/8.x/helpers Converts a singular studly caps word to its plural form. Supports only English. The first example shows basic pluralization, the second shows using an integer second argument to get singular or plural form. ```php use Illuminate\Support\Str; $plural = Str::pluralStudly('VerifiedHuman'); // VerifiedHumans $plural = Str::pluralStudly('UserFeedback'); // UserFeedback ``` ```php use Illuminate\Support\Str; $plural = Str::pluralStudly('VerifiedHuman', 2); // VerifiedHumans $singular = Str::pluralStudly('VerifiedHuman', 1); // VerifiedHuman ``` -------------------------------- ### Example JSON response for assertJsonPath Source: https://laravel.com/framework/docs/8.x/http-tests Example JSON data returned by the application, used to demonstrate assertJsonPath. ```json { "user": { "name": "Steve Schoger" } } ``` -------------------------------- ### Get RoadRunner binary in Sail shell Source: https://laravel.com/framework/docs/8.x/octane Start a Sail shell and use the `rr` executable to download the Linux build of the RoadRunner binary. ```bash ./vendor/bin/sail shell # Within the Sail shell... ./vendor/bin/rr get-binary ``` -------------------------------- ### Install Pusher Channels PHP SDK via Composer Source: https://laravel.com/framework/docs/8.x/broadcasting Run this Composer command to install the Pusher Channels PHP SDK, required when broadcasting with Pusher Channels. ```bash composer require pusher/pusher-php-server ``` -------------------------------- ### get() with default value Source: https://laravel.com/framework/docs/8.x/collections Returns the item at a given key, or a default value if the key does not exist. The example passes 34 as the default for 'age'. ```php $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $value = $collection->get('age', 34); // 34 ``` -------------------------------- ### Install Supervisor on Ubuntu Source: https://laravel.com/framework/docs/8.x/horizon Installs Supervisor, a process monitor for Linux, using apt-get. For non-Ubuntu systems, use the operating system's package manager. ```bash sudo apt-get install supervisor ``` -------------------------------- ### Podcast model without real-time facade (injecting Publisher) Source: https://laravel.com/framework/docs/8.x/facades Shows the original Podcast model that requires a Publisher instance to be injected into the publish method. This is the baseline example before using real-time facades. ```php update(['publishing' => now()]); $publisher->publish($this); } } ``` -------------------------------- ### Install Cashier Paddle via Composer Source: https://laravel.com/framework/docs/8.x/cashier-paddle Run this command to install the Laravel Cashier Paddle package using Composer. ```bash composer require laravel/cashier-paddle ``` -------------------------------- ### Nested Resource URI Example Source: https://laravel.com/framework/docs/8.x/controllers Example URI pattern for a nested resource route defined with dot notation. ```text /photos/{photo}/comments/{comment} ``` -------------------------------- ### nth() - get every n-th element Source: https://laravel.com/framework/docs/8.x/collections Creates a new collection consisting of every n-th element. Example shows usage with default offset. ```php $collection = collect(['a', 'b', 'c', 'd', 'e', 'f']); $collection->nth(4); // ['a', 'e'] ``` -------------------------------- ### Define publish groups with tags in service provider boot method Source: https://laravel.com/framework/docs/8.x/packages In the boot method of a package's service provider, use the publishes method with tags to define separate publish groups. The example defines 'courier-config' and 'courier-migrations' groups for the courier package. ```php /** * Bootstrap any package services. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/../config/package.php' => config_path('package.php') ], 'courier-config'); $this->publishes([ __DIR__.'/../database/migrations/' => database_path('migrations') ], 'courier-migrations'); } ``` -------------------------------- ### Install Laravel Scout via Composer Source: https://laravel.com/framework/docs/8.x/scout Run this command to install the Laravel Scout package via Composer. ```bash composer require laravel/scout ``` -------------------------------- ### modelKeys: Get primary keys of all models Source: https://laravel.com/framework/docs/8.x/eloquent-collections Returns an array of primary keys for all models in the collection. The example shows the result for a collection of five users. ```php $users->modelKeys(); // [1, 2, 3, 4, 5] ``` -------------------------------- ### Create subscription with newSubscription and returnTo Source: https://laravel.com/framework/docs/8.x/cashier-paddle Creates a subscription for the user and returns a pay link. Uses the newSubscription method with a monthly price and a return URL. ```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]); }); ``` -------------------------------- ### Install Chokidar for file watching Source: https://laravel.com/framework/docs/8.x/octane Installs the Chokidar file-watching library as a dev dependency, required for the --watch flag. ```bash npm install --save-dev chokidar ``` -------------------------------- ### Execute PHP code before tasks with @setup Source: https://laravel.com/framework/docs/8.x/envoy Use the @setup directive to define a block of PHP code that executes before your Envoy tasks. ```blade @setup $now = new DateTime; @endsetup ``` -------------------------------- ### count() - Get total number of items Source: https://laravel.com/framework/docs/8.x/collections Returns the total number of items in the collection. The example shows a collection of four items and the result 4. ```php $collection = collect([1, 2, 3, 4]); $collection->count(); // 4 ``` -------------------------------- ### Publish package configuration with publishes() Source: https://laravel.com/framework/docs/8.x/packages Call the publishes method from the boot method of your service provider to allow users to publish the package's configuration file to the application's config directory. When users run vendor:publish, the file is copied to the specified location. ```php /** * Bootstrap any package services. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/../config/courier.php' => config_path('courier.php'), ]); } ``` -------------------------------- ### Install MeiliSearch PHP SDK Source: https://laravel.com/framework/docs/8.x/scout Required when using the MeiliSearch driver. Install the MeiliSearch PHP SDK and HTTP factory via Composer. ```bash composer require meilisearch/meilisearch-php http-interop/http-factory-guzzle ``` -------------------------------- ### Process specific queue with --queue option Source: https://laravel.com/framework/docs/8.x/queues Start a worker that only processes a particular queue on a given connection. For example, process only the emails queue on the redis connection. ```bash php artisan queue:work redis --queue=emails ``` -------------------------------- ### Install Tailwind CSS and generate config Source: https://laravel.com/framework/docs/8.x/mix Install Tailwind CSS via NPM and generate the `tailwind.config.js` file using `npx tailwindcss init`. ```bash npm install npm install -D tailwindcss npx tailwindcss init ``` -------------------------------- ### mode() - get mode value from collection Source: https://laravel.com/framework/docs/8.x/collections Returns the mode value of a given key or of the collection itself. Example shows usage with an array of associative arrays and simple arrays. ```php $mode = collect([ ['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40] ])->mode('foo'); // [10] $mode = collect([1, 1, 2, 4])->mode(); // [1] $mode = collect([1, 1, 2, 2])->mode(); // [1, 2] ``` -------------------------------- ### Write a file to the local disk using Storage::disk('local')->put() Source: https://laravel.com/framework/docs/8.x/filesystem Writes 'Contents' to storage/app/example.txt using the local driver. The root directory defaults to storage/app, so the file is placed there. ```php use Illuminate\Support\Facades\Storage; Storage::disk('local')->put('example.txt', 'Contents'); ``` -------------------------------- ### Share site via Expose Source: https://laravel.com/framework/docs/8.x/valet Navigate to the site directory and run `expose`. Expose displays the sharable URL. Press `Control + C` to stop sharing. Requires Expose to be installed. ```bash cd ~/Sites/laravel expose ``` -------------------------------- ### min() - get minimum value from collection Source: https://laravel.com/framework/docs/8.x/collections Returns the minimum value of a given key or of the collection itself. Example shows usage with an array of associative arrays and a simple array. ```php $min = collect([['foo' => 10], ['foo' => 20]])->min('foo'); // 10 $min = collect([1, 2, 3, 4, 5])->min(); // 1 ``` -------------------------------- ### median() - get median value from collection Source: https://laravel.com/framework/docs/8.x/collections Returns the median value of a given key or of the collection itself. Example shows usage with an array of associative arrays and a simple array. ```php $median = collect([ ['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40] ])->median('foo'); // 15 $median = collect([1, 1, 2, 4])->median(); // 1.5 ``` -------------------------------- ### max() - get maximum value from collection Source: https://laravel.com/framework/docs/8.x/collections Returns the maximum value of a given key or of the collection itself. Example shows usage with an array of associative arrays and a simple array. ```php $max = collect([ ['foo' => 10], ['foo' => 20] ])->max('foo'); // 20 $max = collect([1, 2, 3, 4, 5])->max(); // 5 ``` -------------------------------- ### Create Laravel project with Git repository Source: https://laravel.com/framework/docs/8.x Use the `--git` flag to initialize a Git repository and commit the base Laravel skeleton. Requires Git to be installed and configured. ```bash laravel new example-app --git ``` -------------------------------- ### Arr::only - Get specified key/value pairs Source: https://laravel.com/framework/docs/8.x/helpers Returns only the specified key/value pairs from the given array. The example extracts 'name' and 'price' from an array with three keys. ```php use Illuminate\Support\Arr; $array = ['name' => 'Desk', 'price' => 100, 'orders' => 10]; $slice = Arr::only($array, ['name', 'price']); // ['name' => 'Desk', 'price' => 100] ``` -------------------------------- ### Create and run queue table migration Source: https://laravel.com/framework/docs/8.x/queues Run the queue:table Artisan command to generate a migration for the jobs table, then migrate the database with the migrate command. ```bash php artisan queue:table ``` ```bash php artisan migrate ``` -------------------------------- ### Refresh a model with fresh() Source: https://laravel.com/framework/docs/8.x/eloquent Use the fresh method to re-retrieve the model from the database without affecting the existing instance. The example retrieves a flight and then gets a fresh copy. ```php $flight = Flight::where('number', 'FR 900')->first(); $freshFlight = $flight->fresh(); ``` -------------------------------- ### Define a console command with ask and choice Source: https://laravel.com/framework/docs/8.x/console-tests Example console command that asks for a name and language preference, then outputs a line. Used to demonstrate testing with expectsQuestion and expectsOutput. ```php Artisan::command('question', function () { $name = $this->ask('What is your name?'); $language = $this->choice('Which language do you prefer?', [ 'PHP', 'Ruby', 'Python', ]); $this->line('Your name is '.$name.' and you prefer '.$language.'.'); }); ``` -------------------------------- ### Share site via Ngrok Source: https://laravel.com/framework/docs/8.x/valet Navigate to the site directory and run `valet share`. A public URL is copied to the clipboard. Press `Control + C` to stop sharing. Requires an Ngrok account and authentication token. Additional parameters like `--region=eu` can be passed. ```bash cd ~/Sites/laravel valet share ``` -------------------------------- ### Invoke the 'github' macro Source: https://laravel.com/framework/docs/8.x/http-client After defining the macro, call it from anywhere to create a pending request with the configured headers and base URL. This example sends a GET request to the root path. ```php $response = Http::github()->get('/'); ``` -------------------------------- ### Supervisor configuration for Horizon Source: https://laravel.com/framework/docs/8.x/horizon Example Supervisor configuration file (horizon.conf) that starts and monitors the Horizon process. Ensure stopwaitsecs is greater than the longest running job's duration. ```ini [program:horizon] process_name=%(program_name)s command=php /home/forge/example.com/artisan horizon autostart=true autorestart=true user=forge redirect_stderr=true stdout_logfile=/home/forge/example.com/horizon.log stopwaitsecs=3600 ``` -------------------------------- ### Podcast model with real-time facade (using Facades\App\Contracts\Publisher) Source: https://laravel.com/framework/docs/8.x/facades Shows the same Podcast model but using a real-time facade. The Publisher is resolved from the service container via the Facades prefix, and the publish method no longer requires an injected publisher. ```php update(['publishing' => now()]); Publisher::publish($this); } } ``` -------------------------------- ### flatten() flattens a multi-dimensional collection Source: https://laravel.com/framework/docs/8.x/collections Flattens a multi-dimensional collection into a single dimension. The example shows a collection with a nested 'languages' array, then calls flatten() and all() to get the flattened array. ```php $collection = collect([ 'name' => 'taylor', 'languages' => [ 'php', 'javascript' ] ]); $flattened = $collection->flatten(); $flattened->all(); // ['taylor', 'php', 'javascript']; ``` -------------------------------- ### Travis CI .travis.yml configuration for Dusk Source: https://laravel.com/framework/docs/8.x/dusk Use this .travis.yml configuration to run Dusk tests on Travis CI. It sets up PHP 7.3, Chrome stable, copies .env.testing, installs dependencies, generates an app key, installs the Chrome driver, starts Chrome headless and the PHP server, and runs Dusk. ```yaml language: php php: - 7.3 addons: chrome: stable install: - cp .env.testing .env - travis_retry composer install --no-interaction --prefer-dist - php artisan key:generate - php artisan dusk:chrome-driver before_script: - google-chrome-stable --headless --disable-gpu --remote-debugging-port=9222 http://localhost & - php artisan serve --no-reload & script: - php artisan dusk ``` -------------------------------- ### Basic Controller Example: UserController Source: https://laravel.com/framework/docs/8.x/controllers Shows a basic controller class that extends the base controller and returns a view with a user model. The show method uses User::findOrFail to retrieve the user by ID. ```php User::findOrFail($id) ]); } } ``` -------------------------------- ### substr: Extract substring with Str::of()->substr() Source: https://laravel.com/framework/docs/8.x/helpers Returns the portion of the string specified by the given start and length parameters. Examples show extracting from position 8 and with a length of 5. ```php use Illuminate\Support\Str; $string = Str::of('Laravel Framework')->substr(8); // Framework $string = Str::of('Laravel Framework')->substr(8, 5); // Frame ``` -------------------------------- ### Run Homestead init script (macOS/Linux and Windows) Source: https://laravel.com/framework/docs/8.x/homestead Run bash init.sh on macOS/Linux or init.bat on Windows from the Homestead directory to update additional configuration files. You will be asked whether to overwrite existing Homestead.yaml, after.sh, and aliases files. ```bash // macOS / Linux... bash init.sh ``` ```bash // Windows... init.bat ``` -------------------------------- ### Enable Xdebug by setting SAIL_XDEBUG_MODE in .env Source: https://laravel.com/framework/docs/8.x/sail Add the SAIL_XDEBUG_MODE variable to your .env file to enable Xdebug. The mode 'develop,debug' is shown as an example. This must be set before starting Sail. ```plaintext SAIL_XDEBUG_MODE=develop,debug ``` -------------------------------- ### Query active and cancelled subscriptions using scopes Source: https://laravel.com/framework/docs/8.x/cashier-paddle Use the active() and cancelled() query scopes to retrieve subscriptions in those states. The example shows getting all active subscriptions and all cancelled subscriptions for a user. ```php // Get all active subscriptions... $subscriptions = Subscription::query()->active()->get(); // Get all of the cancelled subscriptions for a user... $subscriptions = $user->subscriptions()->cancelled()->get(); ``` -------------------------------- ### Install Breeze with Inertia Vue or React stack Source: https://laravel.com/framework/docs/8.x/starter-kits Commands to install Breeze with the Inertia.js frontend implementation using Vue or React, then compile assets and run migrations. ```bash php artisan breeze:install vue // Or... php artisan breeze:install react npm install npm run dev php artisan migrate ``` -------------------------------- ### Return a view using the View facade Source: https://laravel.com/framework/docs/8.x/views Use the View facade's make method to return a view. The first argument is the view name, the second is an array of data. ```php use Illuminate\Support\Facades\View; return View::make('greeting', ['name' => 'James']); ``` -------------------------------- ### except method: get models without given primary keys Source: https://laravel.com/framework/docs/8.x/eloquent-collections The except method returns all models that do not have the given primary keys. The example excludes users with IDs 1, 2, and 3. ```php $users = $users->except([1, 2, 3]); ``` -------------------------------- ### Set lock expiration with expireAfter Source: https://laravel.com/framework/docs/8.x/queues Explicitly defines a lock expiration time using the expireAfter method. The example releases the WithoutOverlapping lock three minutes (180 seconds) after the job starts processing. ```php /** * Get the middleware the job should pass through. * * @return array */ public function middleware() { return [(new WithoutOverlapping($this->order->id))->expireAfter(180)]; } ``` -------------------------------- ### Load a package view using package::view syntax Source: https://laravel.com/framework/docs/8.x/packages Once the view path is registered, use the 'package::view' syntax to load a view from the package. This example loads the 'dashboard' view from the 'courier' package. ```php Route::get('/dashboard', function () { return view('courier::dashboard'); }); ``` -------------------------------- ### Mocking Cache facade in a test Source: https://laravel.com/framework/docs/8.x/mocking Test example that mocks the Cache facade's get method using shouldReceive, expecting it to be called once with 'key' and return 'value'. This is used to test the controller action. ```php once() ->with('key') ->andReturn('value'); $response = $this->get('/users'); // ... } } ``` -------------------------------- ### Arr::crossJoin - Cross join arrays to get Cartesian product Source: https://laravel.com/framework/docs/8.x/helpers Cross joins the given arrays, returning a Cartesian product with all possible permutations. The example shows two and three input arrays. ```php use Illuminate\Support\Arr; $matrix = Arr::crossJoin([1, 2], ['a', 'b']); /* [ [1, 'a'], [1, 'b'], [2, 'a'], [2, 'b'], ] */ $matrix = Arr::crossJoin([1, 2], ['a', 'b'], ['I', 'II']); /* [ [1, 'a', 'I'], [1, 'a', 'II'], [1, 'b', 'I'], [1, 'b', 'II'], [2, 'a', 'I'], [2, 'a', 'II'], [2, 'b', 'I'], [2, 'b', 'II'], ] */ ``` -------------------------------- ### Example database URL Source: https://laravel.com/framework/docs/8.x/database An example database URL provided by managed providers like AWS and Heroku, containing all connection information in a single string. ```text mysql://root:[email protected]/forge?charset=UTF-8 ``` -------------------------------- ### Get a model's broadcast channel name with broadcastChannel Source: https://laravel.com/framework/docs/8.x/broadcasting Shows how to call the broadcastChannel method on a model instance to determine its channel name. For example, it returns 'App.Models.User.1' for an App\Models\User model with an id of 1. ```php $user->broadcastChannel() ``` -------------------------------- ### Navigate to a URI with visit method Source: https://laravel.com/framework/docs/8.x/dusk Shows how to navigate to a given URI within the application using the visit method. ```php $browser->visit('/login'); ``` -------------------------------- ### List all proxied sites with proxies command Source: https://laravel.com/framework/docs/8.x/valet Use the 'proxies' command to list all site configurations that are currently proxied. ```bash valet proxies ``` -------------------------------- ### reduce: Reduce collection to a single value Source: https://laravel.com/framework/docs/8.x/collections Reduces the collection to a single value, passing the result of each iteration into the next. The example sums [1, 2, 3] to 6. The $carry starts as null on the first iteration. ```php $collection = collect([1, 2, 3]); $total = $collection->reduce(function ($carry, $item) { return $carry + $item; }); // 6 ``` -------------------------------- ### Arr::last - Get last element passing truth test Source: https://laravel.com/framework/docs/8.x/helpers Returns the last element of an array that passes a given truth test. The example uses a callback to find the last value >= 150, which is 300. ```php use Illuminate\Support\Arr; $array = [100, 200, 300, 110]; $last = Arr::last($array, function ($value, $key) { return $value >= 150; }); // 300 ``` -------------------------------- ### Facade vs helper function comparison Source: https://laravel.com/framework/docs/8.x/facades Shows the equivalence between the View facade and the view helper function. ```php return Illuminate\Support\Facades\View::make('profile'); return view('profile'); ``` -------------------------------- ### Define an option shortcut in signature Source: https://laravel.com/framework/docs/8.x/artisan Shows how to assign a shortcut 'Q' to the --queue option using the '|' delimiter. ```php mail:send {user} {--Q|queue} ``` -------------------------------- ### Listener class with handle method for event discovery Source: https://laravel.com/framework/docs/8.x/events Example listener class that Laravel discovers by scanning for methods starting with 'handle'. The event is type-hinted in the method signature, and Laravel registers it as an event listener for that event. ```php use App\Events\PodcastProcessed; class SendPodcastNotification { /** * Handle the given event. * * @param \App\Events\PodcastProcessed $event * @return void */ public function handle(PodcastProcessed $event) { // } } ``` -------------------------------- ### diff() - Get values not present in another collection Source: https://laravel.com/framework/docs/8.x/collections Compares the collection against another collection or array based on values, returning values in the original that are not present in the given collection. The example returns [1, 3, 5]. ```php $collection = collect([1, 2, 3, 4, 5]); $diff = $collection->diff([2, 4, 6, 8]); $diff->all(); // [1, 3, 5] ``` -------------------------------- ### Create subscription with trialUntil and DateTime Source: https://laravel.com/framework/docs/8.x/billing Use the trialUntil method to specify a DateTime instance for when the trial period should end. ```php use Carbon\Carbon; $user->newSubscription('default', 'price_monthly') ->trialUntil(Carbon::now()->addDays(10)) ->create($paymentMethod); ```