Posts

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

How to Detect n+1 Queries in PHP
How to Detect n+1 Queries in PHP

What is the n+1 Query Problem? The n+1 query problem is a common performance issue in software development. N+1 queries result in many unnecessary database calls. This can lead to your app performing at snail-like speed, especially as the data grows. So, you must be aware of and address n+1 queries to ensure your applications are efficient, responsive, and scalable. N+1 queries occur when an application makes one database query to retrieve an object, and then for each object retrieved, it makes additional queries to fetch related objects. This results in a total of N+1 database queries being executed for N objects, which can significantly reduce the efficiency and performance of the application, especially when dealing with large datasets. This article will explore how to quickly detect and resolve n+1 queries using Application Performance Monitoring (APM) tools. N+1 Queries Illustrated: Let's consider a bookstore application that needs to display a list of authors and their books. The application might first query the database to retrieve all authors (1 query). Then, for each author retrieved, it makes another query to fetch their respective books. If there are 100 authors, this results in 1 (initial query) + 100 (one for each author) = 101 queries in total. This is very inefficient and can severely degrade the performance of the application. To avoid the N+1 query problem, developers often use techniques like eager loading, where related data is loaded in the initial database query itself, or batch fetching, where associated data for multiple objects is retrieved in batches. How do you Detect n+1 Queries? If you have a non-trivial application, you likely have n+1 queries. If your application is built with a web framework like Laravel or Symfony and uses an ORM, you will surely have many n+1 queries. This is because the ORM layer of many modern web frameworks lazy-loads records by default. N+1 query problems will likely go unnoticed in your development and testing environments. Still, they may suddenly ruin the application’s performance when deployed to production, where the number of rows in the database is much higher. The giveaway sign that your application has n+1 queries is an unusually high number of database queries being performed. The queries will usually be sequential and non-overlapping. This is all well and good, but you might be wondering, “Okay, but how do I know how many queries are being performed and if they are ‘sequential and non-overlapping?’” Great question! That’s where Application Performance Monitoring (APM) tools come in. Using an APM Tool to find n+1 Queries: Application Performance Monitoring tools, as the name suggests, are applications you can use to monitor and diagnose issues with your app. Such tools can help you monitor all sorts of performance metrics, including database queries. There are many different APM tools available. For this example, I’ll be using Scout APM. Scout APM makes finding n+1 queries very straightforward because it has a dedicated n+1 insights tab. The n+1 insights tab displays a list of all the endpoints in your application (highlighted red), and for each endpoint, you can see how many queries were run and how long they took. Clicking on an individual endpoint will reveal more in-depth information. On the endpoint details page, you get a very helpful timeline view where you can see when an n+1 showed up, for example, after deploying an update. The screenshot above depicts the condensed view that shows streamlined insights into what's going on with the n+1 queries. Click the SQL button (highlighted blue) here, and Scout will show you the blameworthy SQL query. Backtrace While on the endpoint details page, you can click the Backtrace button to find the exact line of code responsible for the n+1 query. You can see in the image above that Scout backtraced the problematic code down to the exact linecausing the issue. The code snippet is displayed because I use Scout’s GitHub integration. But even If you don’t have the GitHub integration, Scout will still report the culpable code file and line number. Now that we know how to hunt down n+1 queries using an APM let's move on to resolving them. Resolving n+1 Queries To illustrate how to solve an N+1 query problem in a PHP application using an ORM (like Laravel's Eloquent or Doctrine), we’ll revisit the example based on the bookstore application scenario mentioned earlier. Scenario: You have a database with two tables: authorsand books. Each author can have multiple books. Let’s first see the code that causes the N+1 query problem, and then I'll show how to solve it. Code with N+1 Query Problem: // Retrieve all authors $authors = Author::all(); foreach($authors as $author) {    // For each author, retrieve their books$books = $author->books()->get(); // This causes an additional query for each author    // Process the books... } In this code, the first query retrieves all authors, and then, for each author, a new query is executed to fetch their books, leading to n+1 queries. N+1 Query Solution 1: Eager Loading One approach to solving the n+1 query problem is using a strategy called eager loading. With eager loading, you load the related models (in this case, books) in your initial query. // Eager load books with authors in one query $authors = Author::with('books')->get(); foreach($authors as $author) {    // Now, no additional query is made here    $books = $author->books;    // Process the books... } N+1 Query Solution 2: Join Query Sometimes, you might want to use a JOIN statementto fetch everything in a single query. You can do this using raw queries or a query builder supplied by your framework. Raw Query Example (using PDO): $sql = "SELECT * FROM authors JOIN books ON authors.id = books.author_id"; $stmt = $pdo->query($sql); $authorsAndBooks = $stmt->fetchAll(PDO::FETCH_ASSOC); // Process the books accordingly Query Builder Example (in Laravel): $authorsAndBooks = DB::table('authors')    ->join('books', 'authors.id', '=', 'books.author_id')    ->get(); // Process the results accordingly Using a raw query or a query builder allows you to write a more optimized SQL query to fetch the data you need in a single request to the database. N+1 Query Solution 3: Caching Yet another approach to resolving n+1 query problems is to use caching. Caching offers a strategic solution to the n+1 query problem, particularly when data doesn't change frequently. By storing the results of database queries in a cache, subsequent requests can retrieve data from this cache instead of hitting the database again. This significantly reduces the number of queries made to the database, especially for repeated requests. You should note that you can use caching together with either one of the previous solutions. N+1 Queries in PHP: Conclusion Understanding and addressing n+1 queries is crucial for optimizing PHP applications. We've explored what n+1 queries are, how they can silently degrade app performance and the strategies to detect n+1 problems with tools like Scout APM. Resolving n+1 queries isn't just about improving speed; it's about writing smarter, more efficient code. By applying these insights, you can ensure a smoother and faster experience for your users. The post How to Detect n+1 Queries in PHP appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Laravel 11 streamlined configuration files
Laravel 11 streamlined configuration files

One of my favorite features in Laravel 11 is the streamlined configuration files. During the development of Laravel 11 all configuration files were removed from the default Laravel installation. However, a few weeks before release, Taylor decided to re-include a slimmed version of the config files in a default Laravel install but left the option to remove any files or options you don't need. Let's dig a little deeper to understand how this works to avoid mistakes and get the slimmest application possible. After all, the config files can add a lot of noise to your application. You also need to be careful to keep them up-to-date, as they are constantly changing. This combination is why I'm glad to see this feature in Laravel 11. Internally, Laravel merges your configuration file with a framework default. So, if your app has a config/database.php file, it will be merged with Laravel's internal config/database.php file. What's interesting here is the merge. On the surface, this merges top-level options (a shallow merge). This means you can further slim your configuration files by removing any top-level options you do not use. Again, any options in your configuration file will automatically merge with the Laravel defaults. Let's look at a quick example using the following config/app.php file within a Laravel 11 application: <?php return [ 'timezone' => 'America/Kentucky/Louisville', 'custom_option' => 'foo' ]; The resulting configuration would be all of the core app configuration options (app.name, app.env, app.debug, etc) with app.timezone overwritten and your app.custom_option added. This merge works well for files with top-level options. However, some of the configuration files have nested "driver" options. Laravel does a bit more when performing this merge. Although it is not recursive, Laravel will merge some common nested options. For example, database.connections, filesystem.disks, and more. With this additional merge, instead of needing to include all the drivers under database.connections (since it's a top-level option), you may slim this section to only the drivers you use. For example, if you use the default testing and mysql database drivers but also have a custom mysql_replica driver in Laravel 11, your config/database.php file may be: <?php return [ 'connections' => [ 'mysql_replica' => [ 'driver' => 'mysql', 'url' => env('DB_REPLICA_URL'), 'host' => env('DB_REPLICA_HOST', '127.0.0.1'), 'port' => env('DB_REPLICA_PORT', '3306'), 'database' => env('DB_DATABASE', 'laravel'), 'username' => env('DB_REPLICA_USERNAME', 'root'), 'password' => env('DB_REPLICA_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => env('DB_CHARSET', 'utf8mb4'), 'collation' => env('DB_COLLATION', 'utf8mb4_0900_ai_ci'), 'prefix' => '', 'prefix_indexes' => true, 'strict' => true, 'engine' => null, 'options' => extension_loaded('pdo_mysql') ? array_filter([ PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), ]) : [], ], ] ]; Of course, you are welcome to preserve the entire set of default configuration files with all of their options. But if you like Laravel’s new, slimmer application structure and want to reduce the noise in your configuration files to your true customizations, this is the way to go. The post Laravel 11 streamlined configuration files appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Laravel 11 is now released!
Laravel 11 is now released!

Laravel 11 is now released, including a minimum PHP v8.2, a new Laravel Reverb package, streamlined directory structure, and more... Laravel Reverb Laravel Reverb is a new first-party WebSocket server for Laravel applications, bringing real-time communication between client and server. Some of the features of Reverb include. Blazing Fast Reverb is fine-tuned for speed. A single server can support thousands of connections and piping data without the delay and inefficiency of HTTP polling. Seamless Integration Develop with Laravel's broadcasting capabilities. Deploy with Reverb's first-party Laravel Forge integration. Monitor with baked-in support for Pulse. Built for Scale Infinitely increase capacity by utilizing Reverb's built-in support for horizontal scaling using Redis, allowing you to manage connections and channels across multiple servers. Pusher Reverb utilizes the Pusher protocol for WebSockets, making it immediately compatible with Laravel broadcasting and Laravel Echo. Streamlined Directory Structure <iframe width="560" height="315" src="https://www.youtube.com/embed/lQSEBvxuXiU?si=5wL1B2ntkPoTaEeF" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> On a fresh install, the file count has dropped by ~ 69 files. Nice. Check out our post on this complete new Laravel 11 Directory Structure Controllers no longer extend anything by default. No more middleware directory. Currently, Laravel includes nine middleware and many you would never customize. However, if you do want to customize them, that is moved to the App/ServiceProvider. For example: public function boot(): void { EncryptCookies::except(['some_cookie']); } No more Http/Kernel Most of the things you used to could do in the Kernel you can now do in the Bootstrap/App. return Application::configure() ->withProviders () -›withRouting( web: __DIR__.'/../routes/web.php' commands: __DIR__.'/../routes/console.php', ) ->withMiddleware(function(Middleware Smiddleware) { $middleware->web(append: LaraconMiddleware::class): }) Model casts changes <iframe width="918" height="516" src="https://www.youtube.com/embed/2WDtpAHRCMA" title="Laravel 11 moves the Model Casts from a property to a method" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Model casts are now defined as a method instead of a property. When defined as a method we can do other things, like call other methods directly from the casts. Here is an example using a new Laravel 11 AsEnumCollection: protected function casts(): array { return [ 'email_verified_at' => 'datetime', 'password' => 'hashed', 'options'=› AsEnumCollection::of(UserOption::class), ]; } New Dumpable Trait This aims to streamline the core of the framework since multiple classes currently have "dd" or "dump" methods. Plus you can use this Dumpable trait in your own classes: class Stringable implements JsonSerializable, ArrayAccess { use Conditionable, Dumpable, Macroable, Tappable; str('foo')->dd(); str('foo')->dump(); Read more about the new Dumpable Trait. Config Changes Laravel has a lot of config files, and Laravel 11 removes these, and all config options cascade down. The .env has been expanded to include all the options you'd want to set. Read more about the config changes. New Once method <iframe width="918" height="516" src="https://www.youtube.com/embed/cZEK0O3CGto" title="Laravel 11 Once Memoization Helper" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Laravel 11 includes a new once helper method that ensures you'll always get the same value no matter how many times you call an object method. The once function is helpful when you have some code that you want to ensure only ever runs one time. Slimmed default Migrations When you start a new Laravel app, it comes with some default migrations from 2014 and 2019. These now will come with the dates removed and moved into just two files. Watch our Instagram Reel Routes changes By default, there will be only two route files, console.php and web.php. API routes will now become opt-in via php artisan install:api, giving you the API routes file and Laravel Sanctum. The same with websocket broadcasting, php artisan install:broadcasting. New up Health Route <iframe width="568" height="1010" src="https://www.youtube.com/embed/EmvHPg8JpB4" title="New Laravel 11 applications will include a new health /up endpoint. #laravel #laravel11" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Laravel 11 will include a new /up health route that fires a DiagnosingHealthEvent so you can better integrate with up time monitoring. APP_KEY Rotation <iframe width="1280" height="720" src="https://www.youtube.com/embed/0dJMX9RjW9A" title="Taylor at Laracon EU showing the new APP_KEY rotation features of Laravel 11" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> In older versions of Laravel, if you changed your APP_KEY it could lead to broken data in the database. Laravel 11 has a new graceful rotation which will NOT break old encrypted data, using an APP_PREVIOUS_KEYS comma-delimited list .env variable. It will auto re-encrypt the data using new key. Console Kernel Removed The Console Kernel is being removed, and you'll be able to instead define your console commands right in routes/console.php. Named Arguments Named arguments are not covered by Laravel's backwards compatibility guidelines. They may choose to rename function arguments when necessary in order to improve the Laravel codebase. When calling Laravel methods using named arguments should be done cautiously and with the understanding that the parameter names may change in the future. Eager Load Limit <iframe width="918" height="516" src="https://www.youtube.com/embed/n4oiIa6BDqE" title="Laravel 11 will have native support for limiting the number of eagerly loaded results per parent." frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Laravel 11 integrates the code behind the "eager load limit" package: User::select('id', 'name')->with([ 'articles' => fn($query) => $query->limit(5) ])->get(); Read more about Eager Load Limit here. New Artisan Commands New Artisan commands have been added to allow the quick creation of classes, enums, interfaces, and traits: php artisan make:class php artisan make:enum php artisan make:interface php artisan make:trait New Welcome Page <iframe width="1280" height="720" src="https://www.youtube.com/embed/ErpVLcxo3cI" title="The history of the Laravel welcome page, including the new one in Laravel 11" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Along with major updates to Laravel, we'll get a new welcome page when creating a new Laravel application. When will Laravel 11 be released? Laravel 11 will be released on March 12, 2024 PHP 8.2 minimum support This was an early decision, but Laravel 11 apps require a minimum of PHP 8.2. If you are running an older version of PHP, now is a good time to get that upgraded. SQLite 3.35.0+ required If you use a SQLite database, then Laravel 11 will require SQLite 3.35.0 or greater. Doctrine DBAL Removal Laravel is no longer dependent on the Doctrine DBAL and registering custom Doctrines types is no longer necessary for the proper creation and alteration of various column types that previously required custom types. Install Laravel 11 The easiest way to install Laravel 11 is to first set up the Laravel Installer composer global require laravel/installer Then run: laravel new projectname Upgrade to Laravel 11 Laravel Shift is the easiest way to upgrade but you can also follow the upgrade guide in the Laravel docs Laravel Support Policy For all Laravel releases, bug fixes are provided for 18 months and security fixes are provided for 2 years. For all additional libraries, including Lumen, only the latest major release receives bug fixes. Version PHP (*) Release Bug Fixes Until Security Fixes Until Laravel 9 8.0 - 8.2 February 8th, 2022 August 8th, 2023 February 6th, 2024 Laravel 10 8.1 - 8.3 February 14th, 2023 August 6th, 2024 February 4th, 2025 Laravel 11 8.2 - 8.3 March 12th, 2024 September 3rd, 2025 March 12th, 2026 12 8.2 - 8.3 Q1 2025 Q3, 2026 Q1, 2027 Wrapup So far, all these features are considered beta for Laravel 11 and are designed to improve your workflow. Things can and probably change, and we will keep this post updated as new features are announced. The post Laravel 11 is now released! appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Resources for Getting Up To Speed with Laravel 11
Resources for Getting Up To Speed with Laravel 11

Now that Laravel 11 is out, we wanted to share some resources from the community for getting up-to-speed with Laravel 11. Whether you’re a seasoned Laravel developer or just stepping into the world of web development, we’ve hand-picked some content we think will help you get up to speed quickly: Laravel 11 Highlights in 90 Seconds If you’re already familiar with Laravel, we walk you through Laravel 11 highlights in 90 seconds: <iframe width="560" height="315" src="https://www.youtube.com/embed/f41juaJMxKE?si=-pD8L-jK3TwyJ_41" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Dive Into the Streamlined Directory Structure in Laravel 11 Our Dive into the Streamlined Directory Structure in Laravel 11 article walks you through the latest Laravel skeleton directory structure when setting up a new Laravel 11 application. <iframe width="560" height="315" src="https://www.youtube.com/embed/lQSEBvxuXiU?si=gstIKUy4OLMao8Bg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Welcome to Laravel 11 Over on the official Laravel YouTube channel, Christoph Rumpel walks through new features that landed in this week’s Laravel 11 release: <iframe width="560" height="315" src="https://www.youtube.com/embed/rmMCiP-iVYM?si=2rFDo4jOhx5fVZ6g" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Laravel 11 is Here by Josh Cirre Josh Cirre’s video Laravel 11 is Here (and I'm so excited) is another excellent roundup of high-level features released with Laravel 11: <iframe width="560" height="315" src="https://www.youtube.com/embed/IEVufZPXzBo?si=fFvV8D37UWnpqB-F" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Laracasts: 30 Days to Learn Laravel Laracasts has updated their free Laravel course to Laravel 11, 30 Days to Learn Laravel. You’ll learn Laravel from scratch in one month, one video per day, and learn everything you need to start building Laravel apps. This is a free course that anyone can watch! Laravel Reverb Documentation Laravel Reverb, a first-party WebSocket server for Laravel applications, launched with Laravel 11 as well. The full documentation for getting started with Reverb is now available in the official documentation. It will walk you through installing, setting up, and running the Reverb server in production. <iframe width="560" height="315" src="https://www.youtube.com/embed/TkYXIHgdrgA?si=lOlgORQ2yzpFSJ2y" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> The Laravel Reverb website is beautiful, so check it out for a quick overview of Reverb, along with links to the documentation. Upgrade to Laravel 11 with Shift You can automate the Upgrade of Laravel 10.x to Laravel 11.x with Laravel Shift. This is an amazing way to speed up the upgrade process and get those existing Laravel applications running on the latest version of Laravel. Laravel News creator Eric Barnes demonstrates upgrading laravel-news.com to Laravel 11 using the amazing Shift service: <iframe width="560" height="315" src="https://www.youtube.com/embed/Z6aY9FfY5eI?si=9hh-F5U_xj6kB-u2" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> The Laravel 11 shift includes streamlining your configuration files to their true customizations, consolidating service providers, getting your app to reflect the Laravel 11 application structure updates, and more. Check out the Shift demo video for some additional insight. Laravel 11 Documentation Prologue Each Laravel release contains a Prologue section, which contains Release Notes, an Upgrade Guide, and a Contribution Guide. Using Laravel Shift is the best way to upgrade, but reading through the release notes and upgrade guide is an excellent way to familiarize yourself with changes to the latest Laravel version. A quick way to stay current with Laravel releases is the laravelversions.com website (and their APIs) so that you always know where to go to find dates for release, end of bug fixes, and end of security updates for Laravel & PHP. Hat tip to Matt Stauffer, who helps maintain laravelversions.com and phpreleases.com. At the time of release, here’s an updated support policy: Learn More On our Laravel News YouTube channel, we have a Laravel 11 playlist for everything we've published leading up to the release of Laravel 11. We’d love to hear what you’re building with Laravel! The post Resources for Getting Up To Speed with Laravel 11 appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Statamic announces next Flat Camp retreat (EU edition)
Statamic announces next Flat Camp retreat (EU edition)

Statamic's Flat Camp is an unforgettable, relationship-focused retreat for the Statamic and Laravel community. Happening June 11-14, 2024, and set in the idyllic Italian countryside, right outside Rome, surrounded by beautiful scenery, we talk both business and non-business. Spend time with the gentlemen from the Statamic Core team, meet those lovely people from the community IRL, influence the future roadmap, and talk about operating your freelance or agency business to peers, all while sitting by the pool, having lunch or dinner cooked by a private chef, and more! It's a different experience compared to a regular conference you might have attended in the past. You won't need a hotel since the accommodation is included in the ticket as well. This is all part of the experience. Read the recap of last year's retreat over on the Statamic blog or relive some of the magic by watching the recap video. <iframe width="939" height="528" src="https://www.youtube.com/embed/x1kzmJFGTJA" title="Flat Camp 2023" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> It truly was a unique get-together last year. Still need convincing after watching that recap video? Let Jack, founder of Statamic, tell you why you (and/or your colleagues) should come. <iframe width="939" height="528" src="https://www.youtube.com/embed/RHttx8q1VOk" title="Why you should come to Flat Camp – The Statamic Non-Conf" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Flat Camp is limited to 50 guests and a ticket includes: 3 Nights lodging in our own private Italian villa Private chef will prepare us breakfast, lunch, and dinner Access to all workshops, intimate talks, and wine cellar chats Exclusive Statamic/Flat Camp swag Other mysteries and surprises For complete details and tickets, head over to the Flat Camp site. The post Statamic announces next Flat Camp retreat (EU edition) appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.