The essential news about content management systems and mobile technology. Powered by Perfect Publisher and XT Search for Algolia.
The News Site publishes posts to the following channels: Facebook, Instagram, Twitter, Telegram, Web Push, Tumblr, and Blogger.
Laravel 11 is now released, including a minimum PHP v8.2, a new Laravel Reverb package, streamlined directory structure, and more...
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.
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
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']);
}
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 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),
];
}
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.
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.
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.
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
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
.
Laravel 11 will include a new /up
health route that fires a
DiagnosingHealthEvent
so you can better integrate with
up time monitoring.
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.
The Console Kernel is being removed, and you'll be able to
instead define your console commands right in
routes/console.php
.
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.
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 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
Along with major updates to Laravel, we'll get a new welcome page when creating a new Laravel application.
Laravel 11 will be released on March 12, 2024
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.
If you use a SQLite database, then Laravel 11 will require SQLite 3.35.0 or greater.
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.
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
Laravel Shift is the easiest way to upgrade but you can also follow the upgrade guide in the Laravel docs
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.2 | Q1 2023 | August 6th, 2024 | February 4th, 2025 |
Laravel 11 | 8.2 | Q1 2024 | August 5th, 2025 | February 3rd, 2026 |
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 appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.
Read more https://laravel-news.com/laravel-11
Read more https://build.prestashop-project.org/news/2024/upcoming-live-update-march-2024/
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 all the latest Laravel articles like this directly in your inbox.
Read more https://laravel-news.com/laravel11-streamlined-configs
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.
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.
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.
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.
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.
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.
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.
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...
}
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.
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.
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 all the latest Laravel articles like this directly in your inbox.
Read more https://laravel-news.com/how-to-detect-n1-queries-in-php
Want to integrate Cloudflare Turnstile CAPTCHA into your Laravel or Livewire app? This package from Ryan Chandler makes integration super simple.
Include the Turnstile scripts using the
@turnstileScripts
Blade directive in the
<head>
of your layout file.
<html>
<head>
@turnstileScripts()
</head>
<body>
{{ $slot }}
</body>
</html>
After that, use the <x-turnstile />
component
inside a <form>
:
<form action="/" method="POST">
<x-turnstile />
<button>
Submit
</button>
</form>
Use the provided validation rule on the server to validate the CAPTCHA response.
use Illuminate\Validation\Rule;
public function submit(Request $request)
{
$request->validate([
'cf-turnstile-response' => ['required', Rule::turnstile()],
]);
}
This package can also integrate seamlessly with Livewire. Upon
successful validation, the property specified inside of
wire:model
will be updated with the Turnstile
token.
<x-turnstile wire:model="yourModel" />
Check out the package on GitHub for more details on customizing and integrating it into your app.
The post Integrate Cloudflare Turnstile into Laravel and Livewire appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.
Read more https://laravel-news.com/laravel-cloudflare-turnstile
Page 16 of 1312