Posts

Since 2024
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.

Non-backed Enums in Database Queries and a withSchedule() bootstrap method in Laravel 11.1
Non-backed Enums in Database Queries and a withSchedule() bootstrap method in Laravel 11.1

This week, the Laravel team released v11.1 with a withSchedule bootstrap method, non-backed Enums in query builder, SES list management options, and more. Laravel 11.1 is the first minor version release since the GA of Laravel 11, released earlier this month. Add withSchedule to Application Bootstrap Nuno Maduro contributed a withSchedule method to the bootstrap/app.php file: ->withSchedule(function ($schedule) { $schedule->command('backup:database')->daily(); }) List management options added to SES Mail Transport Ariful Alam contributed the ability to use SES's subscription management features while using the SES mail transport. You can define the following header in the headers() method of a mail message: /** * Get the message headers. */ public function headers(): Headers { return new Headers( text: [ 'X-Ses-List-Management-Options' => 'contactListName=MyContactList;topicName=MyTopic', ], ); } This SES header automatically enables unsubscribe links in every outgoing email you specify the contact list and topic. If a user unsubscribes, SES does not allow email sending. See Laravel's SES driver documentationfor further details. Accept Non-backed Enums in Database Queries Giorgio Balduzzi contributed the ability to use non-backed enums in database queries. Casting Eloquent attributes is already possible. However, using non-backed enums with the query builder was not possible. Now, you can pass these enums to queries as of Laravel 11.1: enum Status { case Active; case Archive; } class User extends Model { protected $casts = [ 'status' => Status::class, ]; } User::where('status', Status::Active)->get(); User::update([ 'status' => Status::Archive]); Queries automatically cast each non-backed enum case to the name value. Conditionable Trait Added to Context Michael Nabil contributed adding the Conditionable trait to Laravel's new Context Facade. This allows for conditionally setting context and also defining default values when false or true depending on the conditionable method: Context::when( auth()->user()->isAdmin(), fn ($context) => $context->add('user', ['key' => 'other data', ...auth()->user()]), fn ($context) => $context->add('user', auth()->user()), ); Release notes You can see the complete list of new features and updates below and the diff between 11.0.0 and 11.1.0 on GitHub. The following release notes are directly from the changelog: v11.1.0 [11.x] MySQL transaction isolation level fix by @mwikberg-virta in https://github.com/laravel/framework/pull/50689 [11.x] Add ListManagementOptions in SES mail transport by @arifszn in https://github.com/laravel/framework/pull/50660 [11.x] Accept non-backed enum in database queries by @gbalduzzi in https://github.com/laravel/framework/pull/50674 [11.x] Add Conditionable trait to Context by @michaelnabil230 in https://github.com/laravel/framework/pull/50707 [11.x] Adds [@throws](https://github.com/throws) section to the Context's doc blocks by @rnambaale in https://github.com/laravel/framework/pull/50715 [11.x] Test modifying nullable columns by @hafezdivandari in https://github.com/laravel/framework/pull/50708 [11.x] Introduce HASH_VERIFY env var by @valorin in https://github.com/laravel/framework/pull/50718 [11.x] Apply default timezone when casting unix timestamps by @daniser in https://github.com/laravel/framework/pull/50751 [11.x] Fixes ApplicationBuilder::withCommandRouting() usage by @crynobone in https://github.com/laravel/framework/pull/50742 [11.x] Register console commands, paths and routes after the app is booted by @plumthedev in https://github.com/laravel/framework/pull/50738 [11.x] Enhance malformed request handling by @jnoordsij in https://github.com/laravel/framework/pull/50735 [11.x] Adds withSchedule to bootstrap/app.php file by @nunomaduro in https://github.com/laravel/framework/pull/50755 [11.x] Fix dock block for create method in InvalidArgumentException.php by @saMahmoudzadeh in https://github.com/laravel/framework/pull/50762 [11.x] signature typo by @abrahamgreyson in https://github.com/laravel/framework/pull/50766 [11.x] Simplify ApplicationBuilder::withSchedule() by @crynobone in https://github.com/laravel/framework/pull/50765 The post Non-backed Enums in Database Queries and a withSchedule() bootstrap method in Laravel 11.1 appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Cache Routes with Cloudflare in Laravel
Cache Routes with Cloudflare in Laravel

The Cloudflare Cache package for Laravel provides cacheable routes, allowing you to serve millions of requests for static pages efficiently. You can define a group of cacheable routes with the Laravel router, including tags. This package makes it easy to start caching with Cloudflare using the Route::cache() method: Route::cache(tags: ['tag1', 'tag2'], ttl: 600)->group(function () { Route::get('/content_with_tags', function () { return 'content'; }); }); Route::cache(tags: ['staticPages'])->group(function () { // }); This package gives you APIs to purge all content, specific URLs, prefixes/tagged URLs (enterprise), and more. As an example, let's say you want to cache articles (Posts) with Cloudflare and purge the cache whenever the article is updated: <?php namespace App\Http\Controllers; use App\Http\Requests\UpdatePostRequest; use App\Models\Post; use Yediyuz\CloudflareCache\Facades\CloudflareCache; class PostController extends Controller { public function update(Post $post, UpdatePostRequest $request) { $post->update($request->validated()); CloudflareCache::purgeByUrls([ route('post.show', $post->id) ]); return back()->with('message', 'Post updated and url cache purged'); } You can learn more about this package, get full installation instructions, and view the source code on GitHub. The post Cache Routes with Cloudflare in Laravel appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Add Architecture Tests to Saloon API Integrations with Lawman
Add Architecture Tests to Saloon API Integrations with Lawman

Lawman is a Pest PHP plugin that makes adding arch tests to your application for your API integrations easy, with a set of Saloon Expectations! This weekend I worked on something new and shiny for SaloonPHP. I'd like to introduce you to Lawman.Lawman is a @pestphp plugin that makes adding arch tests to your application for your API integrations easy, with a set of Saloon Expectations!https://t.co/WUIGnHriNo✨🤠— Jon Purvis (@JonPurvis_) February 14, 2024 <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> It is already possible to write architecture tests for Saloon with PestPHP, but Lawman aims to make it quicker to write and easier to read. Take this example of a connector arch test with and without Lawman: // Without Lawman test('connector') ->expect('App\Http\Integrations\Integration\Connector') ->toExtend('Saloon\Http\Connector') ->toUse('Saloon\Traits\Plugins\AcceptsJson') ->toUse('Saloon\Traits\Plugins\AlwaysThrowOnErrors'); // With Lawman test('connector') ->expect('App\Http\Integrations\Integration\Connector') ->toBeSaloonConnector() ->toUseAcceptsJsonTrait() ->toUseAlwaysThrowOnErrorsTrait(); You can see examples and a complete list of expectations available in Lawman by checking out the plugin documentation page in the Saloon docs. The post Add Architecture Tests to Saloon API Integrations with Lawman appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Phone Number Formatting, Validation, and Model Casts in Laravel
Phone Number Formatting, Validation, and Model Casts in Laravel

The Laravel-Phone package makes working with phone numbers in PHP and Laravel a breeze, offering validation rules, attribute casting, utility helpers, and more. Have you ever built validation around phone numbers that supports multiple countries? This package has helpful validation rules built in, which makes it easy to validate numbers for any country. You can specify acceptible country code formats, but at the same time accept valid "international" numbers: // Validate either USA or Belguim Validator::make($request->all(), [ 'phone_number' => 'phone:US,BE', ]); // Validate US specifically, but also accept other countries Validator::make($request->all(), [ 'phone_number' => 'phone:US,INTERNATIONAL', ]); // Use the Phone rule Validator::make($request->all(), [ 'phone_number' => (new Phone)->country(['US', 'BE']), ]); // Match country code against another data field Validator::make($request->all(), [ 'phone_number' => (new Phone)->countryField('custom_country_field'), 'custom_country_field' => 'required_with:phone_number', ]); This package uses the PHP port of Google's phone number handling library under the hood, which has robust parsing, formatting, and validation capabilities for working with phone numbers in PHP: // Formatting examples $phone = new PhoneNumber('012/34.56.78', 'BE'); $phone->format($format); // Custom formatting $phone->formatE164(); // +3212345678 $phone->formatInternational(); // +32 12 34 56 78 $phone->formatRFC3966(); // +32-12-34-56-78 $phone->formatNational(); // 012 34 56 78 You can learn more about this package, get full installation instructions, and view the source code on GitHub. I recommend getting started with the readme for full documentation about this package. The post Phone Number Formatting, Validation, and Model Casts in Laravel appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

VS Code Extension for API Insights
VS Code Extension for API Insights

Recently, at Treblle, we released a Visual Studio Code extension to work with our free developer tool, API Insights. After releasing this new tool, we wanted to look for ways developers building OpenAPI Specifications could benefit without stopping what they were doing. So, for those who need to be made aware, API Insights is a free developer tool we created at Treblle that lets you get insights into your API design. It will score your OpenAPI Specification against: Performance Quality Security The way this works is that we analyze your specification to understand what this API does. We then compare your API to a set of industry standards for APIs and see how close you are to having an "industry standard API". However, we go a step further than just analyzing your specification; we send a request to the first endpoint that could be successful and measure load time and response size. We can analyze something similar to understand your API better. The VS Code extension will allow you to analyze your specifications without leaving your editor. Even better, though, is that it will then watch this file for changes and prompt you to re-run the analysis if a change is detected. We wrote about this new free tool in a little more detail on our blog and would love to hear your thoughts about the extension - also, what developer tool you would find helpful! You never know; we may build it. The post VS Code Extension for API Insights appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

The Evolution of the Laravel Welcome Page
The Evolution of the Laravel Welcome Page

The release of Laravel 11 and Laravel Reverb will happen on Tuesday, March 12, 2024. Along with major updates to Laravel, we'll get a new welcome page when creating a new Laravel application with laravel new or composer. I thought it would be fun to see how the welcome page has evolved over previous versions of Laravel. Whether you are new to the framework or have been around a while, there's something special about creating a new Laravel project and seeing that welcome screen! Laravel 11 Laravel 11 will feature a light and dark theme, which looks gorgeous and inviting. It has a vibrant background, clean icons, and a welcoming feel that inspires creativity: Laravel 11 welcome page (dark mode) Laravel 11 welcome page (light mode) Comparing Laravel 11 (top) to Laravel 10 (bottom) Laravel 10 It's hard to believe that Laravel 10 was released a year ago on February 14, 2023. Over the last year, we've received countless amazing new features and quality-of-life updates. Here's what the welcome page looks like with a fresh Laravel 10 installation: Laravel 10 welcome (dark mode) Laravel 10 welcome (light mode) Notably, the Laravel logo is centered and is only the logo mark. Laravel 9 and 8 had a left-aligned logo + Laravel text mark: Logo mark changes between Laravel 8 and Laravel 10 Laravel 8 The welcome page featured in Laravel 8 was the first time we saw a significant change since Laravel 5.x. Laravel 8 was released on September 8, 2020, during the period of time Laravel released a major version every six months: Laravel 8 dark mode featuring updated Laravel branding Laravel 8 light mode featuring updated Laravel branding Laravel's branding was technically updated around the Laravel 6 release. However, Laravel 8 was the first time the new logo was introduced on the welcome page. It featured four main areas/links: documentation, Laravel News, Laracasts, and prominent ecosystem links. Laravel 5.5 Between Laravel 6 and 7, we didn't see any significant changes to the welcome page, but at some point in the 5.x releases, the welcome page included links to documentation, Laracasts, Laravel News, Forge, and GitHub: Laravel 5.5 welcome page Laravel 5.0 Laravel 5.0's landing page had the words "Laravel 5" and rendered a random inspiring quote using the Inspiring facade: <div class="content"> <div class="title">Laravel 5</div> <div class="quote">{{ Inspiring::quote() }}</div> </div> Laravel 5.0 welcome page Bonus: Laravel 4.2 Laravel 4.2 had a minimal welcome page featuring a nostalgic logo (base64 image) and folder structure, which included this hello.php file, with the text, "You have arrived." Laravel 4.2 hello page The post The Evolution of the Laravel Welcome Page appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.