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, Bluesky, and Blogger.
This week, the Laravel team released v10.34, adding a
missing()
method that applies to route groups, an
alias for the new Number
class, an
extensions
validation rule, and more. Here is a bit
more info about the new features introduced this week:
Ash Allen contributed an update to the Collection
ensure()
method that allows you to pass multiple types
instead of only allowing one type:
collect([new User(), new Contact(), new Contact()])
->ensure([User::class, Contact::class]);
Ronald Edelschaap contributed the ability to add a
missing()
callback for the routes on a group:
// Before
Route::prefix('locations')
->group(function() {
Route::get('{location}', [LocationsController::class, 'show'])
->missing(fn() => ['success' => false, 'message' => 'The requested location does not exist']);
Route::put('{location}', [LocationsController::class, 'update'])
->missing(fn() => ['success' => false, 'message' => 'The requested location does not exist']);
Route::delete('{location}', [LocationsController::class, 'destroy'])
->missing(fn() => ['success' => false, 'message' => 'The requested location does not exist']);
});
// After
Route::prefix('locations')
->missing(fn() => ['success' => false, 'message' => 'The requested location does not exist'])
->group(function() {
Route::get('{location}', [LocationsController::class, 'show']);
Route::put('{location}', [LocationsController::class, 'update']);
Route::delete('{location}', [LocationsController::class, 'destroy']);
});
@eusonlito contributed a file extensions
validation rule that you can use in combination with the
mimes
validation rule:
['file', 'mimes:jpg,jpeg,png', 'extensions:jpg,png']
The extensions rule was added to the Validation documentation, which notes that the
extensions
rule should be used in tandem with
validating the mime type via the mimes
rule.
See Pull Request #49082 for more details.
Jamie York contributed aliasing the Number Utility Class for quick use in Blade templates without needing to import the full namespace:
<p>Percentage: {{ Number::percentage(50) }}</p>
Noboru Shiroiwa contributed adding the
Conditionable
trait to the TestResponse
class, which you can use when asserting the response:
test('name', function ($attributes) {
$user = User::factory()->create($attributes);
$response = $this
->actingAs($user)
->get('/');
$response
->assertOk()
->when($attributes['gender'] === 1, fn () => $response->assertSee('Hello boys!'))
->when($attributes['gender'] === 2, fn () => $response->assertSee('Hello girls!'));
})->with([
'boy' => [
[
'name' => 'Michael',
'gender' => 1,
],
],
'girl' => [
[
'name' => 'Susan',
'gender' => 2,
],
],
]);
You can see the complete list of new features and updates below and the diff between 10.33.0 and 10.34.0 on GitHub. The following release notes are directly from the changelog:
hex_color
validation rule by @apih
in https://github.com/laravel/framework/pull/49070extensions
by @eusonlito in https://github.com/laravel/framework/pull/49082Collection
using WeakMap
by @crynobone in https://github.com/laravel/framework/pull/49095mb_str_pad()
for
Str::pad*
by @amacado in
https://github.com/laravel/framework/pull/49108ensure
method by @ash-jc-allen in https://github.com/laravel/framework/pull/49127false
values in apc
by @simivar in https://github.com/laravel/framework/pull/49145performUpdate
by
@taka-oyama in https://github.com/laravel/framework/pull/49141ensure
: Resolve $itemType
outside the closure by @lucasmichot
in https://github.com/laravel/framework/pull/49137MorphTo::associate()
PHPDoc parameter
by @devfrey in https://github.com/laravel/framework/pull/49162php artisan about
--json
by @crynobone in
https://github.com/laravel/framework/pull/49154Vite
when
using withoutVite()
by @orkhanahmadov in https://github.com/laravel/framework/pull/49150The post Laravel 10.34 Released 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-10-34-0
Laravel Schema Rules is a package that automatically generates basic Laravel validation rules based on your database table schema. You can use this package as a starting point to quickly create boilerplate rules and optimize as needed.
Given the following schema (from in the README) for your table:
Schema::create('persons', function (Blueprint $table) {
$table->id();
$table->string('first_name', 100);
$table->string('last_name', 100);
$table->string('email');
$table->foreignId('address_id')->constrained();
$table->text('bio')->nullable();
$table->enum('gender', ['m', 'f', 'd']);
$table->date('birth');
$table->year('graduated');
$table->float('body_size');
$table->unsignedTinyInteger('children_count')->nullable();
$table->integer('account_balance');
$table->unsignedInteger('net_income');
$table->boolean('send_newsletter')->nullable();
});
You can run the schema:generate-rules
Artisan
command to generate validation rules:
$ php artisan schema:generate-rules persons
[
'first_name' => ['required', 'string', 'min:1', 'max:100'],
'last_name' => ['required', 'string', 'min:1', 'max:100'],
'email' => ['required', 'string', 'min:1', 'max:255'],
'address_id' => ['required', 'exists:addresses,id'],
'bio' => ['nullable', 'string', 'min:1'],
'gender' => ['required', 'string', 'in:m,f,d'],
'birth' => ['required', 'date'],
'graduated' => ['required', 'integer', 'min:1901', 'max:2155'],
'body_size' => ['required', 'numeric'],
'children_count' => ['nullable', 'integer', 'min:0', 'max:255'],
'account_balance' => ['required', 'integer', 'min:-2147483648', 'max:2147483647'],
'net_income' => ['required', 'integer', 'min:0', 'max:4294967295'],
'send_newsletter' => ['nullable', 'boolean']
]
You can also target specific columns, skip columns, and even generate a form request class.
There's also an online version of this package that you can use to experiment with this package or use it to manually take a schema and convert it to an array of validation rules:
Visit validationforlaravel.com to try it out!
You can learn more about this package, get full installation instructions, and view the source code on GitHub.
The post Generate Validation Rules from a Database Schema in Laravel 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-schema-rules
The Filament Feature Flags package by Stephen Jude is a feature segmentation package made with Laravel Pennant. This feature flag package provides a UI to manage configurable features and segments in your Filament application:
This Filament Feature Flags package was released a few weeks
ago, offering the following features in the initial
v1.0
version:
You can learn more about this package, get full installation instructions, and view the source code on GitHub.
The post A Feature Flags Implementation for Filament 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/filament-feature-flags
The best Black Friday deal isn’t a disposable gadget or a trendy clothing item. Instead, consider something that will help you grow and will grow along with you. Your website isn’t just about your online presence—it’s the foundation for everything you hope to achieve.
From today through Cyber Monday (November 27), we’re offering unbeatable deals on website plans and domains.
For a limited time, both our monthly and annual website plans are on sale:
Get half off the first month of any monthly plan when you use the code bf23monthly at checkout.
Get 25% off the entire year when you purchase any 1-year plan. Use the code bf23annual at checkout.
Choose your planThree simple steps for taking advantage of this Black Friday discount:
With over 150 domain extensions on sale, you have unlimited opportunities to express yourself or memorably brand your business. With some domains starting at under $1 for the first year, owning your identity online won’t break the bank.
Visit wordpress.com/domains to start exploring.
Choose your domainThe most popular domains—.com, .net, and .org—are always available for just $12 per year.
These deals are valid for new website and domain purchases only (no renewals or upgrades). The offers are good through the end of the day Monday, November 27, wherever you are in the world.
Read more https://wordpress.com/blog/2023/11/24/black-friday/
The PHP team has released PHP 8.3 today with typed class
constants, a json_validate() function, dynamically fetching a class
constant, the #[Override]
attribute, and more:
In PHP 8.2, it was still not possible to declare constant
(const
) types, which can lead to confusion or
implications about the type you're working with:
interface I {
const TEST = "Test"; // We may naively assume that the TEST constant is always a string
}
class Foo implements I {
const TEST = []; // But it may be an array...
}
class Bar extends Foo {
const TEST = null; // Or null
}
Here's an example of how typed constants look in PHP 8.3:
interface I {
const string TEST = E::TEST; // I::TEST is a string as well
}
class Foo implements I {
use T;
const string TEST = E::TEST; // Foo::TEST must also be a string
}
class Bar extends Foo {
const string TEST = "Test2"; // Bar::TEST must also be a string, but the value can change
}
// Error example
// Fatal error: Cannot use array as value for class constant
// Foo::PHP of type string
class Buzz implements I {
const string PHP = [];
}
To validate JSON in PHP, you would need to either configure the
JSON_THROW_ON_ERROR
flag, use
json_last_error
, or even just check for
null
on a json_decode()
call:
json_decode(json: '{"foo": "bar}', flags: JSON_THROW_ON_ERROR);
// JsonException Control character error, possibly incorrectly encoded.
As of PHP 8.3, you can also validate JSON using the
json_validate()
function:
// Valid
json_validate('{"framework": "Laravel"}'); // true
// Invalid
json_validate('{"framework": "Laravel}'); // false
json_last_error_msg(); // Control character error, possibly incorrectly encoded
json_last_error(); // 3
In PHP >= 8.2, dynamically fetching a class constant value
was only possible using the constant()
function. The
following would result in a syntax error:
class Framework {
const NAME = 'Laravel';
}
$name = 'NAME';
// You could achieve this with the constant() function
constant(Framework::class . '::' . $name); // Laravel
// This following is a syntax error in >=v8.2.0
echo Framework::{$name};
// ParseError syntax error, unexpected token ";", expecting "(".
As of PHP 8.3, you can now access constants dynamically from a class,
class Framework {
const NAME = 'Laravel';
}
$name = 'NAME';
// Syntax error in <= v8.2.0
echo Framework::{$name}; // Laravel
One of my favorite additions to PHP 8.3 is providing a default
value when using environment variables to define INI settings. This
will simplify Docker defaults without having to specify the
defaults as ENV
blocks in a Dockerfile
. I
am sure there are plenty of use cases out there that will be
simplified by this.
Let's say, for example, that you want to allow a
DRUPAL_FPM_PORT
ENV value to configure an INI value
for the www
FPM pool:
error_log = syslog
daemonize = false
[www]
listen = localhost:${DRUPAL_FPM_PORT}
The DRUPAL_FPM_PORT
must be defined, and no default
was possible! Now, you can do the following, which should feel
familiar to a bash/shell script:
[www]
listen = localhost:${DRUPAL_FPM_PORT:-9000}
Imagine shipping an xdebug.ini
file as part of your
Dockerfile for development with sensible defaults yet allowing
developers to override values they see fit.
PHP 8.3 includes Randomizer Additions, including a new
getBytesFromString()
method, which is convenient to
get random bytes from a source string:
$randomizer = new \Random\Randomizer();
printf(
"%s.example.com",
$randomizer->getBytesFromString('abcdefghijklmnopqrstuvwxyz0123456789', 16)
);
// 3zsw04eiubcf82jd.example.com
// Generate a random code for multi-factor authentication
$randomizer = new \Random\Randomizer(new \Random\Engine\Secure());
echo implode('-', str_split($randomizer->getBytesFromString('0123456789', 20), 5));
// 11551-80418-27047-42075
To get up to speed on these new features, check out the PHP 8.3.0 Release Announcement page for examples before/after PHP 8.3. Be sure to check out the deprecations and backward compatibility breaks.
The post PHP 8.3 is released with typed class constants, a json_validate function, and more 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/php-8-3-0