Posts

Since 2024
The Random package generates cryptographically secure random values
The Random package generates cryptographically secure random values

The Random package by Stephen Rees-Carter, generates cryptographically secure random values in a range of different formats through a simple helper package for PHP. Here is why this package was created: Something I commonly encounter during my security audits (especially on older codebases) is insecure randomness, usually in places where security is required. It’s usually using some form of rand(), often injected inside md5() to generate a random hash, combined with str_shuffle() to generate new passwords, or used to make an One-Time Password (OTP) with rand(100_000, 999_999). The problem is rand() is not cryptographically secure, and neither is mt_rand(), mt_srand(), str_shuffle(), array_rand(), or of the other insecure functions available in PHP. We can’t simply declare these methods insecure, drop the mic, and walk away. Instead, we need to provide secure alternatives - so rather than simply saying “don’t use rand() in that way”, we can say “here’s a secure method you can use instead”! Here are some examples of what you can do with this Random package: Random One-Time Password (Numeric fixed-length OTPs) Generate a random numeric one-time password (OTP) of $length digits: $otp = Random::otp(int $length): string; Useful for generating OTPs for SMS or email verification codes. Random String Generate a random string of $length characters, which includes characters from the enabled character types. By default, it will randomly select characters and not guarantee any specific character types are present. If you require one of each character to be included, you can set $requireAll = true. // Primary method $string = Random::string( int $length = 32, bool $lower = true, bool $upper = true, bool $numbers = true, bool $symbols = true, bool $requireAll = false ): string; The string method also comes with nice wrappers for common use cases: // Random letters only $letters = Random::letters(int $length = 32): string; // Random alphanumeric (letters and numbers) token string $token = Random::token(int $length = 32): string; // Random letters, numbers, and symbols (i.e. a random password). $password = Random::password(int $length = 16, bool $requireAll = false): string; // Random alphanumeric token string with chunks separated by dashes, making it easy to read and type. $password = Random::dashed(int $length = 25, string $delimiter = '-', int $chunkLength = 5, bool $mixedCase = true): string; Shuffle Array, String, or Collection Securely shuffle an array, string, or Laravel Collection, optionally preserving the keys. $shuffled = Random::shuffle( array|string|\Illuminate\Support\Collection $values, bool $preserveKeys = false ): array|string|\Illuminate\Support\Collection; And more Visit the official package page on GitHub for complete details, and also check out the announcement post. The post The Random package generates cryptographically secure random values appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Automatic Blade Formatting on Save in PhpStorm
Automatic Blade Formatting on Save in PhpStorm

PhpStorm has good automatic formatting of PHP files based on standards like PSR-2, PSR-12, Symfony, Laravel, etc.; however, there have not been a lot of options for consistently formatting blade files in PhpStorm until recently. There are whispers of Blade formatting coming to Laravel Pint, but another interesting option is using the JavaScript's Prettier code formatting tool with the prettier-plugin-blade plugin. Matt Stauffer's article How to set up Prettier On a Laravel App, Linting Tailwind Class Order and More is an excellent primer to formatting Tailwind and Blade using Prettier. Here's the gist of the Prettier configuration file: { "plugins": ["prettier-plugin-blade", "prettier-plugin-tailwindcss"], "overrides": [ { "files": [ "*.blade.php" ], "options": { "parser": "blade" } } ] } Once you have configured Prettier, you can quickly set up formatting on save in PhpStorm by navigating to Languages & Frameworks > JavaScript > Prettier. Update your settings to reflect the following: Configure Prettier to format Blade files on save. Specifically, you'll want to add blade.php to the "Run for files" pattern. The full pattern should be: **/*.{js,ts,jsx,tsx,vue,astro,blade.php}. Make sure that "Run on save" is checked, and now Blade files will be automatically formatted. If you've enabled the prettier-plugin-tailwindcss plugin, Tailwind classes will be sorted as well! If you want to reformat code manually, you can also use the "Reformat Code" action (the shortcut for me is Alt+Super+l) to format any file using the configured formatter. The Format Code action Related: Jeffrey Way's PhpStorm Setup in 2024 The post Automatic Blade Formatting on Save in PhpStorm appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released
Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released

This week, the Laravel team released v11.3, which includes multi-line text in Laravel Prompts, a Session:hasAny() method, a Context::pull() method, and more. Multi-line Text Prompts Joe Tannenbaum contributed a textarea function to Laravel prompts that accepts multi-line text from a user: Multi-line text input in Laravel Prompts The textarea() function includes an optional validation argument as well as a required argument to make sure the textarea is filled out: use function Laravel\Prompts\textarea; $story = textarea( label: 'Tell me a story.', placeholder: 'This is a story about...', required: true, hint: 'This will be displayed on your profile.' ); // Validation $story = textarea( label: 'Tell me a story.', validate: fn (string $value) => match (true) { strlen($value) < 250 => 'The story must be at least 250 characters.', strlen($value) > 10000 => 'The story must not exceed 10,000 characters.', default => null } ); See the textarea() function documentation for usage details and Pull Request #88 in the laravel/prompts repository for the implementation. New Session hasAny() Method Mahmoud Mohamed Ramadan contributed a hasAny() method to sessions, which is a nice improvement when checking to see if any values are in the session: // Before if (session()->has('first_name') || session()->has('last_name')) { // do something... } // Using the new hasAny() method if (session()->hasAny(['first_name', 'last_name'])) { // do something... } Context Pull Method @renegeuze contributed a pull() and pullHidden() method to the Context service, which pulls the contextual data and immediately removes it from context. $foo = Context::pull('foo'); $bar = Context::pullHidden('foo'); An example use-case for this feature might be capturing context for database logging and pulling it because the additional context is no longer needed. Release notes You can see the complete list of new features and updates below and the diff between 11.2.0 and 11.3.0 on GitHub. The following release notes are directly from the changelog: v11.3.0 [10.x] Prevent Redis connection error report flood on queue worker by @kasus in https://github.com/laravel/framework/pull/50812 [11.x] Optimize SetCacheHeaders to ensure error responses aren't cached by @MinaWilliam in https://github.com/laravel/framework/pull/50903 [11.x] Add session hasAny method by @mahmoudmohamedramadan in https://github.com/laravel/framework/pull/50897 [11.x] Add option to report throttled exception in ThrottlesExceptions middleware by @JaZo in https://github.com/laravel/framework/pull/50896 [11.x] Add DeleteWhenMissingModels attribute by @Neol3108 in https://github.com/laravel/framework/pull/50890 [11.x] Allow customizing TrimStrings::$except by @grohiro in https://github.com/laravel/framework/pull/50901 [11.x] Add pull methods to Context by @renegeuze in https://github.com/laravel/framework/pull/50904 [11.x] Remove redundant code from MariaDbGrammar by @hafezdivandari in https://github.com/laravel/framework/pull/50907 [11.x] Explicit nullable parameter declarations to fix PHP 8.4 deprecation by @Jubeki in https://github.com/laravel/framework/pull/50922 [11.x] Add setters to cache stores by @stancl in https://github.com/laravel/framework/pull/50912 [10.x] Laravel 10x optional withSize for hasTable by @apspan in https://github.com/laravel/framework/pull/50888 [11.x] Fix prompting for missing array arguments on artisan command by @macocci7 in https://github.com/laravel/framework/pull/50850 [11.x] Add strict-mode safe hasAttribute method to Eloquent by @mateusjatenee in https://github.com/laravel/framework/pull/50909 [11.x] add function to get faked events by @browner12 in https://github.com/laravel/framework/pull/50905 [11.x] retry func - catch "Throwable" instead of Exception by @sethsandaru in https://github.com/laravel/framework/pull/50944 chore: remove repetitive words by @findseat in https://github.com/laravel/framework/pull/50943 [10.x] Add serializeAndRestore() to NotificationFake by @dbpolito in https://github.com/laravel/framework/pull/50935 [11.x] Prevent crash when handling ConnectionException in HttpClient retry logic by @shinsenter in https://github.com/laravel/framework/pull/50955 [11.x] Remove unknown parameters by @naopusyu in https://github.com/laravel/framework/pull/50965 [11.x] Fixed typo in PHPDoc [@param](https://github.com/param) by @naopusyu in https://github.com/laravel/framework/pull/50967 [11.x] Fix dockblock by @michaelnabil230 in https://github.com/laravel/framework/pull/50979 [11.x] Allow time to be faked in database lock by @JurianArie in https://github.com/laravel/framework/pull/50981 [11.x] Introduce method Http::createPendingRequest() by @Jacobs63 in https://github.com/laravel/framework/pull/50980 [11.x] Add @throws to some doc blocks by @saMahmoudzadeh in https://github.com/laravel/framework/pull/50969 [11.x] Fix PHP_MAXPATHLEN check for existing check of files for views by @joshuaruesweg in https://github.com/laravel/framework/pull/50962 [11.x] Allow to remove scopes from BelongsToMany relation by @plumthedev in https://github.com/laravel/framework/pull/50953 [11.x] Throw exception if named rate limiter and model property do not exist by @mateusjatenee in https://github.com/laravel/framework/pull/50908 The post Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite
Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite

The Bartender package for Laravel is an opinionated way to authenticate users using Laravel Socialite. Bartender serves you a controller, routes, and a default implementation for handling authentication with Laravel Socialite providers. Almost everything in Bartender can be customized. Using the configuration conventions, you can enable social logins by defining the routes and configuring the providers you're app will support: // routes/web.php use DirectoryTree\Bartender\Facades\Bartender; Bartender::routes(); // config/services.php return [ // ... 'google' => [ // ... 'redirect' => '/auth/google/callback', ], 'microsoft' => [ // ... 'redirect' => '/auth/microsoft/callback', ], ]; Bartender takes care of everything for you from here; however, you can also extend and customize everything from OAuth redirects and callbacks, user creation and handling, and user redirects and flash messaging. You can learn more about this package, get full installation instructions, and view the source code on GitHub. You can install this package in your Laravel app with Composer: $ composer require directorytree/bartender $ php artisan vendor:publish --provider="DirectoryTree\Bartender\BartenderServiceProvider" $ php artisan migrate The post Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Jeffrey Way's PhpStorm Setup in 2024
Jeffrey Way's PhpStorm Setup in 2024

Call it age. Call it apathy, if you must. I call it contentment. Much of my twenties were spent endlessly experimenting and searching for the perfect editor and workflow. As I read these words back to myself, I’m somewhat embarrassed. “Really? That’s what you spent your twenties doing?” Okay, well, not exclusively. I also like hiking. But, yes, if a new editor hit the market, I was first in line to test it out. But that was a long time ago. Fast-forward to 2024, and I can’t remember the last time I installed a new code editor. In my eyes, PhpStorm won the IDE wars years ago. The quality and power that they’ve managed to bake into one application is truly staggering. So, in that spirit, I’d love to share my setup and general workflow with you. As you’ll soon see, the term IDE no longer suggests an incredibly dense UI with hundreds of buttons (though that’s an option, if you prefer). No, I prefer a more minimal approach that I think you’ll appreciate. Okay, let’s do this! Default Works for Me When it comes to color themes, it has taken me a decade to realize that one of your IDE’s suggested defaults is usually the way to go. A plugin containing hundreds of themes, each of which misses the mark in some key area, isn’t a great experience. But your editor’s default themes have been battle tested in every possible configuration. With that in mind, my preference these days is PhpStorm’s Dark theme, combined with their “New UI” (now the default layout). Similarly, I also stick with the default JetBrains Mono font at 15px. Yes, it seems that age is becoming a recurring theme for this article. Fifteen pixels looks good to me now. You’ll notice that I’ve also hidden line numbers and tabs. This is of course a personal preference - and a questionable one to many - however, it’s worth experimenting with for a day. If you’d like to test it out, like all of PhpStorm’s various actions, you can toggle line numbers and tabs using the “Search Anywhere” menu, which defaults to a keybinding of “Shift + Shift.” Search for “line numbers” and “tab placement,” respectively. For file traversal, I use a combination of the “Search Anywhere” and “Recent Files” menus. Even better, because all of PhpStorm’s file trees allow for instant filtering, I only need to open the “Recent Files” menu and begin typing the first few characters of the file that I want to open. It’s an incredibly fast workflow. Plugins When it comes to plugins, the truth is that PhpStorm includes most of what you need straight out of the box. Support for Tailwind CSS, Vue, Pest, Vite, and Node - to name a small handful - are bundled from the start. As a former Vim user who will never abandon the keybindings that I spent over a year drilling into my finger tips, I do pull in IdeaVim, which is effectively a Vim engine. And if you want to play around with custom UIs and themes, consider installing the Material Theme UI, Nord or Carbon plugins. But - there’s one incredibly important plugin that deserves its own heading… Laravel Idea is the Secret Weapon PhpStorm has a secret weapon that I’ve yet to see any competing editor match. Laravel Idea is a cheap third-party plugin (with a free 30 day trial) that provides an incredibly deep understanding of the Laravel framework. It provides powerful code generation directly from your editor, Eloquent attribute auto-completion, pre-populated validation rules, smart routing completion, and so much more. Laravel Idea is the only plugin I pay for, and I do it without thinking. It’s that good. Code Generation Of course, Laravel and Artisan provide a variety of generators that can be triggered from the command line. However, if you prefer, you can instead run these generators directly within PhpStorm. Navigate to the “Laravel” tab in the menu bar, and choose “Code Generation.” Here, you can choose your desired file type to generate. It’s so fast. Notably, when generating an Eloquent model, you’ll be introduced to a dedicated dialog for configuring your desired fields, relations, and options. Here, I can declare all of the appropriate fields for the model and toggle any companion files that should be generated in the process. Automatic Validation Rules Let’s see another example. Imagine that you have an endpoint in your routes file that stores a new Job in the database. Certainly, you should first validate the request data. Rather than writing the rules manually, Laravel Idea can do it for you. Route::post('/jobs', function () { request()->validate([ // ]); }); Place the caret within the validate() array, press Cmd + n, and choose “Add Eloquent Model Fields.” Type the name of the relevant model, Job, and the plugin will populate the array with the appropriate rules, like so: Route::post('/jobs', function () { request()->validate([ 'employer_id' => ['required', 'exists:employers'], 'title' => ['required'], 'salary' => ['required'], ]); }); Useful! Laravel Idea provides countless time-savers just like this. It’s an essential plugin for every Laravel user, in my opinion. Refactor This The best argument for a dedicated IDE is that you want an editor that deeply understands your underlying language. If I need to rename a variable, implement an interface, or extract a method, I don’t want to rely on regular expressions or a third-party extension. I want that functionality baked into the editor. I want these things working properly to be directly correlated to the financial success of Jetbrains. If you’re anything like me, you probably have keyboard shortcuts seeping out of your ears at this point. It’s incredible that we can remember so many across a wide range of apps. With that in mind, while there are respective shortcuts for each of PhpStorm’s refactoring options, I use the catch-all “Refactor This” menu, which I bind to Ctrl + t. Open “Search Anywhere” and type “Refactor This” to open the menu manually. This will display a top-level refactoring menu, at which point I can select my preferred refactor. As always, begin typing to instantly filter the menu items. If I need to, say, extract a method, I would type “extract” and press enter. That way, I never have to reach for the mouse. An Integrated Terminal Beginning with the 2024 edition of PHPStorm, you’ll find a new integrated terminal UI that’s significantly improved over previous iterations. It now supports auto completion, command history (press up), isolated command blocks, and more. I’d recommend binding the integrated Terminal to a shortcut that you’ll remember - I prefer "Ctrl + ` (Backtick)" or Now, you can rapidly toggle the terminal without ever leaving your editor. Seamless Testing Testing in PhpStorm is a breeze. Whether you prefer PHPUnit or Pest, it has you covered. Open any test class or file, and you’ll find a Run icon beside each test definition. Give it a click to run that single test in isolation directly inside your editor. Of course, not every test will pass. For this reason, it can often be useful to re-run the last test from anywhere in your project. This way, you can open a class, make a change, and instantly re-run the failing test to confirm that the issue has been resolved. The command you want for this behavior is “Rerun.” To avoid touching the mouse, consider assigning a keybinding, such as “Shift + Command + T.” Tip: You can configure your own keybindings within Settings → Keymap. In the screenshot above, notice that the commented-out line in Comment.php has triggered a failing test. Let’s fix the issue by uncommenting that line (if only all bugs were this easy to solve), and rerunning the test (using Shift + Command + T). Wew! Auto-formatting PhpStorm of course includes support for automatic code formatting in a variety of code styles. Within the Settings menu, visit Editor → Code Style → PHP and click “Set From” to choose your style. This is helpful, but if you’d instead prefer an external code formatter such as Laravel Pint, you can easily instruct PhpStorm to disable its internal formatter in favor of your external tool. This is precisely what I do. Open your Settings menu once again, and visit PHP → Quality Tools. Here, you’ll find a handful of external formatters. Select “Laravel Pint” and you should be all set to go! Next, it would be nice if we could instruct PhpStorm to perform a series of actions or commands each time we save a file. For example, format the file, optimize the imports (sort and remove unused), clean up the code, run ESLint, etc. This is what the “Actions on Save” menu is for. You can access it within the Settings menu, as usual: Tools → Actions on Save. Select your preferred actions, and the editor will execute them each time you save a file. Debugging Despite what its creator may suggest - 👀 - Xdebug can often be an exercise in frustration to install. It’s clear, though, that the PhpStorm team is well aware of this. They’ve done an excellent job making the process as simple and obvious as possible. Let me show you. The first stop on your debugging journey is Settings → PHP → Debug. On this page, you’ll see a “Pre-Configuration” checklist to verify that you’ve properly installed Xdebug. Helpful! This checklist roughly consists of installing Xdebug, choosing a browser toolbar extension, enabling listening for PHP Debug Connections, and then starting a debug session. I would highly suggest using the validator that PhpStorm links to in pre-configuration step one. Validation Heads Up! If you’re using Herd Pro to automatically detect and enable Xdebug on the fly, PhpStorm’s configuration validator will fail if you simply copy the contents of phpinfo() directly from the command line (php —info | pbcopy). Instead, signal to Herd that you intend to use Xdebug. One way to do this is by setting a breakpoint. Click inside the gutter for any line number. Next, echo phpinfo() and copy its output directly from the browser. Once you follow each step in the pre-configuration checklist, you should be ready to roll. Set a breakpoint, load the page, and start debugging like the champion you are. Conclusion And that’s a wrap! You may have noticed, but programmers tend to have… opinions. When it comes to code editors, they have even more opinions. Of course, choose the tool that best fits your personality and workflow, but I really do think PhpStorm is worth your time. Having used it for many years at this point, I continue to discover new features and time-savers that I never knew existed. If I’ve piqued your interest, we have an excellent and free PhpStorm course over at Laracasts. In 2.5 hours, we’ll show you everything you need to know. 🚀 The post Jeffrey Way's PhpStorm Setup in 2024 appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Easily Optimize PDFs in Laravel with the Optimizer Package
Easily Optimize PDFs in Laravel with the Optimizer Package

This PDF Optimizer package for PHP and Laravel applications for effortless optimization and compression of PDF files. PDF Optimizer utilizes Ghostscript to significantly reduce PDF file sizes. The PDF Optimizer package can be used in any PHP project but also offers Laravel-specific APIs that streamline working with PDF file optimization: use Mostafaznv\PdfOptimizer\Laravel\Facade\PdfOptimizer; use Mostafaznv\PdfOptimizer\Enums\ColorConversionStrategy; use Mostafaznv\PdfOptimizer\Enums\PdfSettings; $result = PdfOptimizer::fromDisk('local') ->open('input-1.pdf') ->toDisk('s3') ->settings(PdfSettings::SCREEN) ->colorConversionStrategy( ColorConversionStrategy::DEVICE_INDEPENDENT_COLOR ) ->colorImageResolution(50) ->optimize('output-1.pdf'); dd($result->status, $result->message); Another useful Laravel-specific feature is the ability to queue the optimization of your files: use Mostafaznv\PdfOptimizer\Laravel\Facade\PdfOptimizer; $result = PdfOptimizer::fromDisk('minio') ->open('input.pdf') ->toDisk('files') ->onQueue() ->optimize('output.pdf'); Other key features this package offers: Fluent Method Chaining: Experience the elegance of a fluent and expressive API that seamlessly optimizes PDF files. Harness the power of nearly all Ghostscript options with ease. Logger Support: Capture detailed logs to gain profound insights into the intricacies of the optimization process. Stay informed and in control with the integrated logger. Customization: Tailor the optimization process to your exact needs. pdf-optimizer provides a customizable solution, allowing you to fine-tune your PDF optimization experience. Laravel Integration: Specifically designed for Laravel applications, pdf-optimizer supports diverse input methods, including file paths, UploadedFile instances, and disk storage. This guarantees flexibility and user-friendly integration within the Laravel ecosystem. Queue Support: Elevate your optimization process with asynchronous PDF file optimization using Laravel queues. pdf-optimizer seamlessly integrates with Laravel's queue system, ensuring efficient background processing. You can get started with this package by checking out the official PDF Optimizer documentation; the source code is also available on GitHub at mostafaznv/pdf-optimizer. The post Easily Optimize PDFs in Laravel with the Optimizer Package appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Create Preview Deployments on Forge with Laravel Harbor
Create Preview Deployments on Forge with Laravel Harbor

Laravel Harbor is a CLI tool that allows you to quickly create on-demand preview environments for your app on Laravel Forge. Using this CLI, you can use GitHub actions to automatically deploy your branches when pull requests are created and tear down the deployment from your server when the pull request is merged. Here's an example of a provisioning workflow using GitHub actions (taken from the documentation): name: preview-provision on: pull_request: types: [opened, edited, reopened, ready_for_review] jobs: harbor-provision: if: | github.event.pull_request.draft == false && contains(github.event.pull_request.title, '[harbor]') runs-on: ubuntu-latest container: image: kirschbaumdevelopment/laravel-test-runner:8.1 steps: - name: Install Harbor via Composer run: composer global require mehrancodes/laravel-harbor -q - name: Start Provisioning env: FORGE_TOKEN: ${{ secrets.FORGE_API_TOKEN }} FORGE_SERVER: ${{ secrets.FORGE_SERVER_ID }} FORGE_GIT_REPOSITORY: ${{ github.repository }} FORGE_GIT_BRANCH: ${{ github.head_ref }} FORGE_DOMAIN: harbor.com run: harbor provision Once you've configured this CLI to run with GitHub actions, pull requests will get updated comments with test environment details, making it easy to see what your preview environment is for testing a feature: Other features include: Seamless Forge integration Automated environment keys Ready for Laravel and Nuxt.js Flexible deployment scripts Customizable deployment workflows Enable SSR for Inertia Post-deployment actions: Slack announcement notifications GitHub announcement commands And more To get started with Harbor and read the official docs, check out laravel-harbor.com. You'll need to have a Laravel Forge account as well; see Harbor's Prerequisites for details. Also, the CLI's source code is available on GitHub at mehrancodes/laravel-harbor if you want to check it out. The post Create Preview Deployments on Forge with Laravel Harbor appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Use the New Fluent Helper to Work With Multi-dimensional Arrays in Laravel 11.2
Use the New Fluent Helper to Work With Multi-dimensional Arrays in Laravel 11.2

This week, the Laravel team released v11.2, which includes a fluent() support helper, a context() helper, improved handling of a missing database during a migrate operation, and more. Fluent Helper Philo Hermans contributed a fluent() helper function when working with multi-dimensional arrays. The Fluent class has been in the Laravel framework for quite a while; however, this PR introduces a helper convenience method to create a fluent object instance: $data = [ 'user' => [ 'name' => 'Philo', 'address' => [ 'city' => 'Amsterdam', 'country' => 'Netherlands', ] ], 'posts' => [ [ 'title' => 'Post 1', ], [ 'title' => 'Post 2', ] ] ]; collect($data)->get('user'); fluent($data)->user; collect($data)->get('user')['name']; fluent($data)->get('user.name'); collect(collect($data)->get('posts'))->pluck('title'); fluent($data)->collect('posts')->pluck('title'); json_encode(collect($data)->get('user')['address']); fluent($data)->scope('user.address')->toJson(); Context Helper Michael Nabil contributed a convenience context() helper function for managing Context. Depending on the arguments passed, you can either add to context, get the context object, or retrieve it (with an optional custom default): // Add user information to the context context(['user' => auth()->user()]); // Retrieve the context object $context = context(); // Retrieve user information from the context $user = context('user'); // Optional custom default value if not found. $some_key = context('key_that_does_not_exist', false); Default Value for Context Getters Michael Nabil contributed support for a default value on Context getters: // Before: Returns null if not found Context::get('is_user'); Context::getHidden('is_user'); // After: Returns `false` if not found Context::get('is_user', false); // false Context::getHidden('is_user', false); // false Context::get('is_user'); // null Job Chain Test Assertion Methods Günther Debrauwer contributed assertHasChain() and assertDoesntHaveChain() methods: public function test_job_chains_foo_bar_job(): void { $job = new TestJob(); $job->handle(); $job->assertHasChain([ new FooBarJob(); ]); // $job->assertDoesntHaveChain(); } Better database creation/wipe handling Dries Vints contributed better database failure handing (#50836) when running migrate when a database isn't created yet, as well as updating the migrate:fresh command to streamline the process when a database does not exist #50838: If the migrate:fresh command is called while there isn't any database created yet, it'll fail when it tries to wipe the database. This PR fixes this by first checking if the migrations table exists and if not, immediately go to the migrate command by skipping the db:wipe command. This will invoke the migrate command flow and subsequently will reach the point where the command will ask the user to create the database. In combination with #50836 this will offer a more seamless experience for people attempting to install Jetstream through the Laravel installer and choosing to not create the database. The above description is taken from Pull Request #50838. String Trim Removes Invisible Characters Dasun Tharanga contributed an update to the framework TrimStrings middleware, where invisible characters are not trimmed during an HTTP request, which can cause issues when submitting forms. See Pull Request #50832 for details. Release notes You can see the complete list of new features and updates below and the diff between 11.1.0 and 11.2.0 on GitHub. The following release notes are directly from the changelog: v11.2.0 [11.x] Fix: update [@param](https://github.com/param) in some doc block by @saMahmoudzadeh in https://github.com/laravel/framework/pull/50827 [11.x] Fix: update @return in some doc blocks by @saMahmoudzadeh in https://github.com/laravel/framework/pull/50826 [11.x] Fix retrieving generated columns on legacy PostgreSQL by @hafezdivandari in https://github.com/laravel/framework/pull/50834 [11.x] Trim invisible characters by @dasundev in https://github.com/laravel/framework/pull/50832 [11.x] Add default value for get and getHidden on Context by @michaelnabil230 in https://github.com/laravel/framework/pull/50824 [11.x] Improves serve Artisan command by @nunomaduro in https://github.com/laravel/framework/pull/50821 [11.x] Rehash user passwords when logging in once by @axlon in https://github.com/laravel/framework/pull/50843 [11.x] Do not wipe database if it does not exists by @driesvints in https://github.com/laravel/framework/pull/50838 [11.x] Better database creation failure handling by @driesvints in https://github.com/laravel/framework/pull/50836 [11.x] Use Default Schema Name on SQL Server by @hafezdivandari in https://github.com/laravel/framework/pull/50855 Correct typing for startedAs and virtualAs database column definitions by @ollieread in https://github.com/laravel/framework/pull/50851 Allow passing query Expression as column in Many-to-Many relationship by @plumthedev in https://github.com/laravel/framework/pull/50849 [11.x] Fix Middleware::trustHosts(subdomains: true) by @axlon in https://github.com/laravel/framework/pull/50877 [11.x] Modify doc blocks for getGateArguments by @saMahmoudzadeh in https://github.com/laravel/framework/pull/50874 [11.x] Add [@throws](https://github.com/throws) to doc block for resolve method by @saMahmoudzadeh in https://github.com/laravel/framework/pull/50873 [11.x] Str trim methods by @patrickomeara in https://github.com/laravel/framework/pull/50822 [11.x] Add fluent helper by @PhiloNL in https://github.com/laravel/framework/pull/50848 [11.x] Add a new helper for context by @michaelnabil230 in https://github.com/laravel/framework/pull/50878 [11.x] assertChain and assertNoChain on job instance by @gdebrauwer in https://github.com/laravel/framework/pull/50858 [11.x] Remove redundant getDefaultNamespace method in some classes (class, interface and trait commands) by @saMahmoudzadeh in https://github.com/laravel/framework/pull/50880 [11.x] Remove redundant implementation of ConnectorInterface in MariaDbConnector by @saMahmoudzadeh in https://github.com/laravel/framework/pull/50881 [11.X] Fix: error when using orderByRaw in query before using cursorPaginate by @ngunyimacharia in https://github.com/laravel/framework/pull/50887 The post Use the New Fluent Helper to Work With Multi-dimensional Arrays in Laravel 11.2 appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

A Package to Generate Custom Stubs in Laravel
A Package to Generate Custom Stubs in Laravel

Laravel Stub is a package that aims to enhance your development workflow in Laravel by providing a set of customizable stubs. Using the project's LaravelStub facade, you can manage stubs with the following API: // Given the following stub file: // // namespace {{ NAMESPACE }}; // // class {{ CLASS }} // { // // // } use Binafy\LaravelStub\Facades\LaravelStub; LaravelStub::from(__DIR__ . 'model.stub') ->to(__DIR__ . '/app') ->name('new-model') ->ext('php') ->replaces([ 'NAMESPACE' => 'App', 'CLASS' => 'Example' ]) ->generate(); Given the above code, the file will be created with the following contents using the model stub: <?php namespace App; class Example { // } Another interesting idea in this package is the download() method, which you can use to force a download in a controller if you want to provide stubs via your application: LaravelStub::from(__DIR__ . 'model.stub') ->to(__DIR__ . '/App') ->name('new-model') ->ext('php') ->replaces([ 'NAMESPACE' => 'App', 'CLASS' => 'Example' ]) ->download(); This package could be an efficient way to provide stub files in your package or application that you want to allow other developers to override with their own customizations. To get started with this package—including installation and usage instructions—check it out on GitHub at binafy/laravel-stub. The post A Package to Generate Custom Stubs in Laravel appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Event sourcing in Laravel with the Verbs package
Event sourcing in Laravel with the Verbs package

Verbs is an Event Sourcing package for Laravel created by Thunk.dev. It aims to take all the good things about event sourcing and remove as much boilerplate and jargon as possible. Verbs allows you to derive the state of your application from the events that have occurred. Learn about the history of Verbs Here is an interview with Daniel Coulbourne, one of the creators of Verbs, that gives details on the project and why you might want to use Event Sourcing: <iframe width="560" height="315" src="https://www.youtube.com/embed/asv-zcluV5Q?si=YY-gjZ-aSV3hpPaH&start=326" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> Verbs work great for the following... Applications that need to be auditable Applications whose schema may change over time Applications with complex business logic What is Event Sourcing? Instead of knowing just the current state of your app, every change (event) that leads to the current state is stored. This allows for a more granular understanding of how the system arrived at its current state and offers the flexibility to reconstruct or analyze the state at any point in time. Learn more about Verbs Visit the official Verbs documentation for complete details on the package, a Quickstart guide, and more. The post Event sourcing in Laravel with the Verbs package appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Creating Your Own PHP Helpers in a Laravel Project
Creating Your Own PHP Helpers in a Laravel Project

Laravel provides many excellent helper functions that are convenient for doing things like working with arrays, file paths, strings, and routes, among other things like the beloved dd() function. You can also define your own set of helper functions for your Laravel applications and PHP packages, by using Composer to import them automatically. If you are new to Laravel or PHP, let’s walk through how you might go about creating your own helper functions that automatically get loaded by Laravel. Creating a Helpers file in a Laravel App The first scenario you might want to include your helper functions is within the context of a Laravel application. Depending on your preference, you can organize the location of your helper file(s) however you want, however, here are a few suggested locations: app/helpers.php app/Http/helpers.php I prefer to keep mine in app/helpers.php in the root of the application namespace. Autoloading To use your PHP helper functions, you need to load them into your program at runtime. In the early days of my career, it wasn’t uncommon to see this kind of code at the top of a file: require_once ROOT . '/helpers.php'; PHP functions cannot be autoloaded. However, we have a much better solution through Composer than using require or require_once. If you create a new Laravel project, you will see an autoload and autoload-dev keys in the composer.json file: "autoload": { "classmap": [ "database/seeds", "database/factories" ], "psr-4": { "App\\": "app/" } }, "autoload-dev": { "psr-4": { "Tests\\": "tests/" } }, If you want to add a helpers file, composer has a files key (which is an array of file paths) that you can define inside of autoload: "autoload": { "files": [ "app/helpers.php" ], "classmap": [ "database/seeds", "database/factories" ], "psr-4": { "App\\": "app/" } }, Once you add a new path to the files array, you need to dump the autoloader: composer dump-autoload Now on every request the helpers.php file will be loaded automatically because Laravel requires Composer’s autoloader in public/index.php: require __DIR__.'/../vendor/autoload.php'; Defining Functions Defining functions in your helpers class is the easy part, although, there are a few caveats. All of the Laravel helper files are wrapped in a check to avoid function definition collisions: if (! function_exists('env')) { function env($key, $default = null) { // ... } } This can get tricky, because you can run into situations where you are using a function definition that you did not expect based on which one was defined first. I prefer to use function_exists checks in my application helpers, but if you are defining helpers within the context of your application, you could forgo the function_exists check. By skipping the check, you’d see collisions any time your helpers are redefining functions, which could be useful. In practice, collisions don’t tend to happen as often as you’d think, and you should make sure you’re defining function names that aren’t overly generic. You can also prefix your function names to make them less likely to collide with other dependencies. Helper Example I like the Rails path and URL helpers that you get for free when defining a resourceful route. For example, a photos resource route would expose route helpers like new_photo_path, edit_photo_path`, etc. When I use resource routing in Laravel, I like to add a few helper functions that make defining routes in my templates easier. In my implementation, I like to have a URL helper function that I can pass an Eloquent model and get a resource route back using conventions that I define, such as: create_route($model); edit_route($model); show_route($model); destroy_route($model); Here’s how you might define a show_route in your app/helpers.php file (the others would look similar): if (! function_exists('show_route')) { function show_route($model, $resource = null) { $resource = $resource ?? plural_from_model($model); return route("{$resource}.show", $model); } } if (! function_exists('plural_from_model')) { function plural_from_model($model) { $plural = Str::plural(class_basename($model)); return Str::kebab($plural); } } The plural_from_model() function is just some reusable code that the helper route functions use to predict the route resource name based on a naming convention that I prefer, which is a kebab-case plural of a model. For example, here’s an example of the resource name derived from the model: $model = new App\LineItem; plural_from_model($model); // => line-items plural_from_model(new App\User); // => users Using this convention you’d define the resource route like so in routes/web.php: Route::resource('line-items', 'LineItemsController'); Route::resource('users', 'UsersController'); And then in your blade templates, you could do the following: <a href="{{ show_route($lineItem) }}"> {{ $lineItem->name }} </a> Which would produce something like the following HTML: <a href="http://localhost/line-items/1"> Line Item #1 </a> Packages Your Composer packages can also use a helpers file for any helper functions you want to make available to projects consuming your package. You will take the same approach in the package’s composer.json file, defining a files key with an array of your helper files. It’s imperative that you add function_exists() checks around your helper functions so that projects using your code don’t break due to naming collisions. You should choose proper function names that are unique to your package, and consider using a short prefix if you are afraid your function name is too generic. Learn More Check out Composer’s autoloading documentation to learn more about including files, and general information about autoloading classes. The post Creating Your Own PHP Helpers in a Laravel Project appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Fast Server-Side Code Highlighting with Tempest
Fast Server-Side Code Highlighting with Tempest

The Tempest highlight package by Brent Roose released v1.0 yesterday, offering a fast, extensible, server-side code highlighting for HTML and terminal in PHP: require __DIR__.'/vendor/autoload.php'; use Tempest\Highlight\Highlighter; use Tempest\Highlight\Themes\LightTerminalTheme; $highlighter = new Highlighter(new LightTerminalTheme()); $code = <<<'CODE' <?php require __DIR__.'/vendor/autoload.php'; use Tempest\Highlight\Highlighter; use Tempest\Highlight\Themes\LightTerminalTheme; $highlighter = new Highlighter(new LightTerminalTheme()); CODE; echo "\n", $highlighter->parse($code, 'php'), "\n\n\n"; Given the above code example, here's what the syntax highlighting looks like in the console: Tempest Highlight with Light Theme Note: the built-in theme in the tempest/highlight package is for a light terminal theme, and it seems easy to provide your own highlighter theme for the console 👍 At the time of writing, v1.0.0 was released, and supports the following languages (and a few I wasn't familiar with): Blade CSS DocComment Gdscript HTML JavaScript JSON PHP SQL Twig XML YAML You can add your own languages or extend them easily. Check out the package's readme on adding or extending languages. This package also has a commonmark integration which you can use to highlight code blocks and inline code. Learn More You can learn more about this package, get full installation instructions, and view the source code on GitHub. The readme has info about special tags for emphasis, strong, blur, and additions/deletions, etc. Brent Roose wrote A syntax highlighter that doesn't suck, which gives you the background on why he created the tempest/highlight package. The post Fast Server-Side Code Highlighting with Tempest appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Generate Code Coverage in Laravel With PCOV
Generate Code Coverage in Laravel With PCOV

Laravel has every testing tool you'll need to productively write feature and unit tests, giving you more confidence in your code and fewer bugs. Using an out-of-the-box installation, we can immediately see coverage reports with artisan using the --coverage flag: php artisan test --coverage If you don't have PCOV or Xdebug installed yet, you'll get the following error: ERROR Code coverage driver not available. Did you install Xdebug or PCOV? Depending on your operating system and PHP installation, you might need to install PCOV or build it using the installation documentation. I am using macOS, so I can install PCOV using Shivam Mathur's homebrew-extensions tap for Homebrew: brew install shivammathur/extensions/pcov@8.3 Once you have installed Xdebug or PCOV, you can get a text version of your coverage report: $ php artisan test --coverage ... Tests: 26 passed (76 assertions) Duration: 2.53s Http/Controllers/Auth/VerifyEmailController ............. 18 / 80.0% Http/Controllers/Controller ................................. 100.0% Livewire/Actions/Logout ..................................... 100.0% Livewire/Forms/LoginForm .................... 53..60, 62..61 / 55.6% Models/User ................................................. 100.0% Providers/AppServiceProvider ................................ 100.0% Providers/VoltServiceProvider ............................... 100.0% View/Components/AppLayout ................................... 100.0% View/Components/GuestLayout ................................... 0.0% Total: 74.4 % Very nice! HTML Reports We can get a more detailed coverage report in other formats, including my favorite for development, an HTML report: vendor/bin/pest --coverage-html=build/coverage Using the --coverage-html flag will create a coverage report in your project, at the build/coverage path, and you can open the index.html file to see it in the browser: HTML coverage in Laravel Note: It's ideal that you ignore the path you intend to use for coverage reports, in my case I would add build to .gitignore. PHPUnit has many coverage options available. For a complete list, you can run phpunit --help. Configuring Coverage in phpunit.xml I prefer using CLI flags to create coverage reports so that I can generate HTML reports in development and Clover reports during CI builds. You might, however, want to configure coverage to run each time you run pest or phpunit: <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true" > <!-- ... --> <coverage> <report> <html outputDirectory="build/coverage"/> <text outputFile="build/coverage.txt"/> <clover outputFile="build/logs/clover.xml"/> </report> </coverage> </phpunit> The above coverage configuration creates an HTML, text, and clover coverage artifact. Now, each time you run your test suite, it will generate coverage reports. I prefer the flexibility of using CLI flags to generate coverage, but XML configuration might be preferable to some. You can learn more about the <coverage> tag in the PHPUnit XML Configuration File reference. How is Coverage Determined? To produce accurate coverage, PHPUnit needs to know which code you own to include in the coverage report. Defining the <include> element is recommended, which Laravel does by default when you create a project. You only have to change this if you want/have nonstandard paths for application source code. Here's what the <source> section should look like on a typical Laravel app installation: <source> <include> <directory>app</directory> </include> </source> If you're using some sort of module pattern, you might need to include other directories to reflect accurate coverage outside of the app folder. Also, PCOV needs to know about these other directories, or you'll get 0% coverage in other app folders. Why? Because PCOV attempts to find src, lib, or app when pcov.directory is left unset. We can demonstrate this by creating a sample file so you can visualize how to set this up. Coverage With Nonstandard Code Paths I recommend sticking the Laravel's conventions, but you might run into situations where you work on existing code that has source code in other places besides the app folder. We can configure PHPUnit and PCOV to include this code as part of the coverage report, with a few tweaks. Let's mimic this; assuming you're starting in a fresh Laravel app, create an example module: # inside a Laravel app mkdir -p module/Example/src Add the following to Example.php in the src folder of the example module: <?php namespace Module\Example; class Example { public function sayHello($name = 'World') { return "Hello, {$name}!"; } } Next, we need to autoload this code to run a test covering this example class. Open composer.json and add the following autoload line: "autoload": { "psr-4": { "App\\": "app/", "Module\\Example\\": "module/Example/src/", "Database\\Factories\\": "database/factories/", "Database\\Seeders\\": "database/seeders/" } } After updating the composer.json file, run composer dumpautoload to update the autoloader and find the new path. As I mentioned before, PHPUnit needs to know about the locations of our source code. Open phpunit.xml and update the <source> configuration to include our module: <source> <include> <directory>app</directory> <directory>module/*/src</directory> </include> </source> Next, create a test file so we can illustrate a 0% coverage report for our module: php artisan make:test --unit ExampleModuleTest Add the following to the created ExampleModuleTest.php file: use Module\Example\Example; test('it says hello', function () { $subject = new Example(); expect($subject->sayHello())->toEqual('Hello, World!'); }); If you run the test suite now, you'll get a 0% coverage report for the module folder: vendor/bin/pest --coverage-html=build/coverage If you open up the latest coverage report, you'll notice the missing coverage, even though the test is passing: Missing module coverage We can fix this by changing a few PCOV configuration options: php -d pcov.enabled=1 -d pcov.directory=. -dpcov.exclude="~vendor~" \ vendor/bin/pest --coverage-html=build/coverage In a typical Laravel application structure, we don't have to do this because the coverage report will look for the app folder automatically. However, if your project needs to report coverage in other paths, we have to set the pcov.directory to the project's root. Since the vendor folder is in the project's root and we never want to scan vendor, we can give PCOV the pcov.exclude pattern. If you run the above and then refresh the HTML report, you should see coverage reported! Working module coverage in a Laravel app Including these PCOV options is tedious, so I prefer to add some composer scripts to do this for me: "scripts": { "test:html": [ "Composer\\Config::disableProcessTimeout", "php -d pcov.enabled=1 -d pcov.directory=. -dpcov.exclude=\"~vendor~\" vendor/bin/pest --coverage-html=build/coverage" ] } You can now run composer test:html to generate an HTML coverage report. I also like to define a test:ci script, which I can use for continuous integration (clover) and upload the coverage artifact to a service like Sonar. You now have all the tools needed to generate coverage reports for Laravel applications and account for coverage in nonstandard paths when your project requires it! The post Generate Code Coverage in Laravel With PCOV appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.