Posts

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

Query Builder whereAll() and whereAny() Methods Added to Laravel 10.47
Query Builder whereAll() and whereAny() Methods Added to Laravel 10.47

The Laravel team released v10.47 this week, which added the whereAll and whereAny methods to the query builder, the ability to use sorting flags with the Collection sortByMany method, and more. This week will likely be the last release to the 10.x branch before Laravel 11’s release on Tuesday, March 12th, 2024. Laravel 10 will continue to receive bug fixes until August 6th, 2024, and security fixes until February 4th, 2025. New whereAll and whereAny query builder methods @musiermoore contributed a new whereAll and whereAny methods to the query builder, along with orWhereAll and orWhereAny methods. These new methods can search against multiple columns using or or and logic // Before using `orWhere` User::query() ->where(function ($query) use ($search) { $query ->where('first_name', 'LIKE', $search) ->orWhere('last_name', 'LIKE', $search) ->orWhere('email', 'LIKE', $search) ->orWhere('phone', 'LIKE', $search); }); // Using `whereAny` User::whereAny( [ 'first_name', 'last_name', 'email', 'phone' ], 'LIKE', "%$search%" ); Here’s an example of using whereAll, in which all columns would need to match using AND: $search = 'test'; User::whereAll([ 'first_name', 'last_name', 'email', ], 'LIKE', "%$search%"); /* SELECT * FROM "users" WHERE ( "first_name" LIKE "%test%" AND "last_name" LIKE "%test%" AND "email" LIKE "%test%" ) */ You can combine multiple like this using orWhereAll and orWhereAny methods. Support Sort Option Flags on sortByMany Collections Tim Withers contributed the ability to pass multiple sorting options to the Collection sortBy method. Before this update, you could accomplish this using multiple callables, but using PHP’s sorting flags: // Pull Request before example $this->campaigns = $campaigns ->with('folder', 'campaignCategory') ->get() ->sortBy([ fn ($a, $b) => str($a->folder?->name)->lower() <=> str($b->folder?->name)->lower(), fn ($a, $b) => str($a->campaignCategory->name)->lower() <=> str($b->campaignCategory->name)->lower(), fn ($a, $b) => str($a->name)->lower() <=> str($b->name)->lower(), ]) // Using sorting flags $this->campaigns = $campaigns ->with('folder', 'campaignCategory') ->get() ->sortBy(['folder.name', 'campaignCategory.name', 'name'], SORT_NATURAL | SORT_FLAG_CASE) You can learn more about sorting flags from the sort function in the PHP manual. Set $failOnTimeout on Queue Listeners Saeed Hosseini contributed the ability to set the $failOnTimeout property on the queue job that indicates if the job should fail if the timeout is exceeded: class UpdateSearchIndex implements ShouldQueue { public $failOnTimeout = false; } Release notes You can see the complete list of new features and updates below and the diff between 10.46.0 and 10.47.0 on GitHub. The following release notes are directly from the changelog: v10.47.0 [10.x] Allow for relation key to be an enum by @AJenbo in https://github.com/laravel/framework/pull/50311 Fix for "empty" strings passed to Str::apa() by @tiagof in https://github.com/laravel/framework/pull/50335 [10.x] Fixed header mail text component to not use markdown by @dmyers in https://github.com/laravel/framework/pull/50332 [10.x] Add test for the "empty strings in Str::apa()" fix by @osbre in https://github.com/laravel/framework/pull/50340 [10.x] Fix the cache cannot expire cache with 0 TTL by @kayw-geek in https://github.com/laravel/framework/pull/50359 [10.x] Add fail on timeout to queue listener by @saeedhosseiinii in https://github.com/laravel/framework/pull/50352 [10.x] Support sort option flags on sortByMany Collections by @TWithers in https://github.com/laravel/framework/pull/50269 [10.x] Add whereAll and whereAny methods to the query builder by @musiermoore in https://github.com/laravel/framework/pull/50344 [10.x] Adds Reverb broadcasting driver by @joedixon in https://github.com/laravel/framework/pull/50088 The post Query Builder whereAll() and whereAny() Methods Added to Laravel 10.47 appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Tailwind has Open-sourced the V4 Alpha
Tailwind has Open-sourced the V4 Alpha

The Tailwind team announced that they are open-sourcing their progress on the Tailwind CSS v4 alpha. This version is a very early peek into something that will be an incredible way to write CSS for web applications. Here’s what we know from the announcement about V4 so far: Tailwind V4 will still support tailwind.config.js to make migrating to v4 easy, but the future is a CSS-first configuration experience: @import "tailwindcss"; @theme { --color-*: initial; --color-gray-50: #f8fafc; --color-gray-100: #f1f5f9; --color-gray-200: #e2e8f0; /* ... */ --color-green-800: #3f6212; --color-green-900: #365314; --color-green-950: #1a2e05; } Another feature from the announcement post that caught my eye was the zero-configuration content detection. Tailwind will crawl your project, looking for template files and using built-in heuristics to find templates. The stable v4 release will include support for explicitly defined content paths, but I love the overall aim of less or zero configuration in V4 😍 Playing with an early Tailwind CSS v4 alpha in a @vite_js project —🚫 No `postcss.config.js file🚫 No `tailwind.config.js` file🚫 No configuring `content` globs🚫 No `@ tailwind` directives in your CSSThe future is clean ✨Hoping to open-source this week for the bold 🤙🏻 pic.twitter.com/zY7vyF1iTs— Adam Wathan (@adamwathan) March 3, 2024 <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> The v4 engine is a ground-up rewrite, taking all the learnings so far and making things faster. Here is what we know about the new engine so far: Up to 10x faster A smaller footprint It’s using Rust in expensive and parallelizable parts of the framework Only one dependency (Lightening CSS) For those ready to try it out, remember that this is an alpha build, and the team has a lot more work to get to V4. You can get started with the Alpha in a few ways: Vite, PostCSS, or CLI. See the “Try out the Alpha” section of the release announcement to get started. See Open-sourcing our progress on Tailwind CSS v4.0 for the full announcement! The post Tailwind has Open-sourced the V4 Alpha appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.