Posts

Since 2024
Basset is an alternative way to load CSS & JS assets
Basset is an alternative way to load CSS & JS assets

It's 2024 and I'm calling it - Server-Side Rendering has officially made a comeback: in Laravel, where Livewire now has 46.000 installs per day in Ruby on Rails with Hotwire in Phoenix with Liveview in web dev in general with HTMX Now that "the old has become the new"... maybe it's time to re-visit another practice we've adopted from the Javascript ecosystem. Maybe it's time to... drop the build step? Crazy, I know! But there's been a lot of talk about no-build Laravel setups in my bubble. And there's one place where people invariably get stuck - "If we drop NPM, what do we do about JS dependencies?". Here's my answer to that - or at least an important first step. What if instead of installing our JS dependencies with a package manager like NPM and bundling them... we just load them directly from the URL? You know... similarly to what the founder of NodeJS himself is doing in Deno. He has publicly said NPM has become a mess and created an alternative for the JS ecosystem... why don't we do the same for the Laravel ecosystem? If you dream about the simple days when you could just load assets using asset(), try Basset - a better asset helper for Laravel. You just replace asset() with basset() to gain some super-powers: assets from CDNs are downloaded to /storage and served from there; vendor assets become possible to load; non-public assets become possible to load; it becomes impossible to double-load an asset during a request; In short, basset() removes the limitations of asset(), allowing you to load any asset you want, safely. That means in addition to this: <link href="{{ asset('path/to/public/file.css') }}"> You can safely do this: <script src="{{ basset(storage_path('file.js')) }}"> <script src="{{ basset(base_path('vendor/org/package/assets/file.js')) }}"> <script src="{{ basset('https://cdn.com/path/to/file.js') }}"> This is a very simple solution for those who want to load assets "the old easy way" in their Laravel projects, because it solves a few problems with that "old way": Don't want GDPR issues? ✅ Solved - Basset will cache the asset to /storage and serve it from there. Don't want to depend on a CDN being up? ✅ Solved - the assets can be cached upon deployment (or on commit). Don't want to load an asset twice, if used by multiple components on that page? ✅ Solved - automatically. Concerned about the performance of loading multiple JS files vs one big bundle? ✅ Solved by HTTP/2, which makes it performant to load multiple Javascript assets on a single page. Granted, Basset may not be a perfect asset loading solution. At least not for every project. It's only been around for 12 months, so it's missing things like importmaps and the like, to make it a 1-to-1 alternative to NPM and Deno's way. But it has been around for 12 months and has proven its usefulness. Perhaps... it's time for us to take another look at how we load assets in our Laravel projects. Maybe we'll discover the simple way... is a good way. For some projects, at least. I suggest you give Basset a try. After all: it's been in production for 1 year already; it's maintained by the Backpack team; it's got 110.000 downloads already; it's under MIT License; If you have feedback on it, open an issue on Github and tell the team about it. A v2 is due soon enough, and we want to incorporate as much feedback as possible. The post Basset is an alternative way to load CSS & JS assets appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4
Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4

This week, the Laravel team released v11.4, with reversible form Prompts, a new Exceptions facade, Enum support in the Collection::mapInto() method, and more. Introduce the Exceptions Facade Nuno Maduro contributed the Exceptions facade: The Exceptions facade provides a consistent way to test exceptions in Laravel applications. Here is the list of methods that the Exceptions facade provides: assertReported assertReportedCount assertNotReported assertNothingReported throwOnReport throwFirstReported Here's an example from the pull request description illustrating the Exceptions::fake() method and assertReported() method: use Illuminate\Support\Facades\Exceptions; test('example', function () { Exceptions::fake(); $this->post('/generate-report', [ 'throw' => 'true', ])->assertStatus(503); // Service Unavailable Exceptions::assertReported(ServiceUnavailableException::class); // or Exceptions::assertReported(function (ServiceUnavailableException $exception) { return $exception->getMessage() === 'Service is currently unavailable'; }); }); See the Exception Handling section of the HTTP Tests documentation for usage details. Livewire-style Directives @devajmeireles contributed the ability to use Boolean-style directives, without any defined value: {{-- Before --}} <x-fetch wire:poll /> {{-- Generates this HTML --}} <div ... wire:poll="wire:poll" /> {{-- After --}} <x-fetch wire:poll /> <div ... wire:poll /> Reversible Forms in Prompts Luke Downing contributed form prompts, which are a grouped set of prompts for the user to complete. Forms include the ability to return to previous prompts and make changes without having to cancel the command and start over: use function Laravel\Prompts\form;   $responses = form() ->text('What is your name?', required: true) ->password('What is your password?', validate: ['password' => 'min:8']) ->confirm('Do you accept the terms?') ->submit(); Here's an example of using values from previous responses: $responses = form() ->text('What is your name?', name: 'name') ->add(fn () => select('What is your favourite language?', ['PHP', 'JS']), name: 'language') ->add(fn ($responses) => note("Your name is {$responses['name']} and your language is {$responses['language']}")) ->submit(); See Pull Request #118 in the laravel/prompts project for implementation details. This feature is already documented in the Prompts documentation. Add Support for Enums on mapInto Collection Method Luke Downing contributed support for Enums on the Collection::mapInto() method, which allows you to build up enums from an array of values: public function store(Request $request) { $request->validate([ 'features' => ['array'], 'features.*' => [new Enum(Feature::class)], ]); $features = $request ->collect('features') ->mapInto(Feature::class); if ($features->contains(Feature::DarkMode)) { // ... } } An afterQuery() Hook Günther Debrauwer contributed an afterQuery() hook to run code after running a query: $query->afterQuery(function ($models) { // Make changes to the queried models ... }); Here's a use-case example from the pull request's description: // Before public function scopeWithIsFavoriteOf($query, ?User $user = null) : void { if ($user === null) { return $query; } $query->addSelect([ // 'is_favorite' => some query ... ]); } $products = Product::withIsFavoriteOf(auth()->user())->get(); if (auth()->user() === null) { $products->each->setAttribute('is_favorite', false); } And here's the code using the afterQuery() hook: // After public function scopeWithIsFavoriteOf($query, ?User $user = null) : void { if ($user === null) { $query->afterQuery(fn ($products) => $products->each->setAttribute('is_favorite', false)); return; } $query->addSelect([ // 'is_favorite' => some query ... ]); } Product::withIsFavoriteOf(auth()->user())->get(); Release notes You can see the complete list of new features and updates below and the diff between 11.3.0 and 11.4.0 on GitHub. The following release notes are directly from the changelog: v11.4.0 [11.x] Apc Cache - Remove long-time gone apc_* functions by @serpentblade in https://github.com/laravel/framework/pull/51010 [11.x] Allowing Usage of Livewire Wire Boolean Style Directives by @devajmeireles in https://github.com/laravel/framework/pull/51007 [11.x] Introduces Exceptions facade by @nunomaduro in https://github.com/laravel/framework/pull/50704 [11.x] afterQuery hook by @gdebrauwer in https://github.com/laravel/framework/pull/50587 Fix computed columns mapping to wrong tables by @maddhatter in https://github.com/laravel/framework/pull/51009 [11.x] improvement test for string title by @saMahmoudzadeh in https://github.com/laravel/framework/pull/51015 [11.x] Fix failing afterQuery method tests when using sql server by @gdebrauwer in https://github.com/laravel/framework/pull/51016 [11.x] Fix: Apply database connection before checking if the repository exist by @sjspereira in https://github.com/laravel/framework/pull/51021 [10.x] Fix error when using orderByRaw() in query before using cursorPaginate() by @axlon in https://github.com/laravel/framework/pull/51023 [11.x] Add RequiredIfDeclined validation rule by @timmydhooghe in https://github.com/laravel/framework/pull/51030 [11.x] Adds support for enums on mapInto collection method by @lukeraymonddowning in https://github.com/laravel/framework/pull/51027 [11.x] Fix prompt fallback return value when using numeric keys by @jessarcher in https://github.com/laravel/framework/pull/50995 [11.x] Adds support for int backed enums to implicit Enum route binding by @monurakkaya in https://github.com/laravel/framework/pull/51029 [11.x] Configuration to disable events on Cache Repository by @serpentblade in https://github.com/laravel/framework/pull/51032 Revert "[11.x] Name of job set by displayName() must be honoured by S… by @RobertBoes in https://github.com/laravel/framework/pull/51034 chore: fix some typos in comments by @laterlaugh in https://github.com/laravel/framework/pull/51037 Name of job set by displayName() must be honoured by Schedule by @SCIF in https://github.com/laravel/framework/pull/51038 Fix more typos by @szepeviktor in https://github.com/laravel/framework/pull/51039 [11.x] Fix some doc blocks by @saMahmoudzadeh in https://github.com/laravel/framework/pull/51043 [11.x] Add @throws ConnectionException tag on Http methods for IDE support by @masoudtajer in https://github.com/laravel/framework/pull/51066 [11.x] Add Prompts textarea fallback for tests and add assertion tests by @lioneaglesolutions in https://github.com/laravel/framework/pull/51055 Validate MAC per key by @timacdonald in https://github.com/laravel/framework/pull/51063 [11.x] Add throttle method to LazyCollection by @JosephSilber in https://github.com/laravel/framework/pull/51060 [11.x] Pass decay seconds or minutes like hour and day by @jimmypuckett in https://github.com/laravel/framework/pull/51054 [11.x] Consider after_commit config in SyncQueue by @hansnn in https://github.com/laravel/framework/pull/51071 [10.x] Database layer fixes by @saadsidqui in https://github.com/laravel/framework/pull/49787 [11.x] Fix context helper always requiring $key value by @nikspyratos in https://github.com/laravel/framework/pull/51080 [11.x] Fix expectsChoice assertion with optional multiselect prompts. by @jessarcher in https://github.com/laravel/framework/pull/51078 The post Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4 appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

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.