With Laravel 10.44 you can add Model Scopes and Observers using PHP Attributes
Last updated on by Paul Redmond
The Laravel team released v10.44 this week with two Eloquent model attributes to define global scopes and observers, a new select() collection method, and more:
New ScopedBy attribute for models
Eliezer Margareten contributed a ScopedBy
attribute to register global scopes on your Eloquent models:
use App\Models\Scopes\AncientScope;use Illuminate\Database\Eloquent\Attributes\ScopedBy; #[ScopedBy([AncientScope::class])]class User extends Model{ //}
You can continue to use the booted()
method in a model to register global scopes:
/** * The "booted" method of the model. */protected static function booted(): void{ static::addGlobalScope(new AncientScope);}
The ScopedBy
attribute accepts a single observer or an array of observers, and you can also define multiple attributes for your model:
// Array type#[ScopedBy([ScopeOne::class, ScopeTwo::class])] // Repeatable string type#[ScopedBy(ScopeOne::class)]#[ScopedBy(ScopeTwo::class)]
New ObservedBy attribute for models
Eliezer Margareten contributed an ObservedBy
attribute to register model observers on your Eloquent models:
use App\Observers\UserObserver;use Illuminate\Database\Eloquent\Attributes\ObservedBy; #[ObservedBy([UserObserver::class])]class User extends Authenticatable{ //}
The ObservedBy
attribute accepts a single observer or an array of observers, and you can also define multiple attributes for your model if that’s your style:
// Array of classes#[ObservedBy([UserObserver::class, AnotherObserver::class])] // Repeatable as string#[ObservedBy(UserObserver::class)]#[ObservedBy(AnotherObserver::class)]
The ObservedBy
attribute is an additional way to register observers, which is traditionally done in a service provider:
public function boot(): void{ User::observe(UserObserver::class);}
The select() Collection method
Craig Morris contributed a new Collection::select()
method that selects a certain number of keys from a multi-dimensional array. The select()
method is similar to an SQL SELECT
statement:
$users = collect([ ['name' => 'Taylor Otwell', 'role' => 'Developer', 'status' => 'active'], ['name' => 'Victoria Faith', 'role' => 'Researcher', 'status' => 'active'],]); $users->select(['name', 'role']); /* [ ['name' => 'Taylor Otwell', 'role' => 'Developer'], ['name' => 'Victoria Faith', 'role' => 'Researcher'], ],*/
Base64 String Methods
Mark Townsend contributed toBase64()
and fromBase64()
to Str and Stringable. These methods wrap base64_encode()
and base64_decode()
respectively:
// Using Str$encoded = Str::toBase64('laravel-news.com');$decoded = Str::fromBase64($encoded); // Using Stringable$encoded = str('laravel-news.com')->toBase64();$decoded = str($encoded)->fromBase64();
Here’s some example output from a tinker
session:
New Arr::take() Method
Ryan Chandler contributed a Arr::take()
method to take a certain number of items from an array. It will take from the front of the array with positive numbers and from the end of the array given a negative number:
$data = [1, 2, 3, 4, 5, 6, 7, 8, 9]; Arr::take($data, 3); // [1, 2, 3]Arr::take($data, -3); // [7, 8, 9]Arr::take($data, 0); // []Arr::take($data, 1); // [1]Arr::take($data, -1); // [9]
Release notes
You can see the complete list of new features and updates below and the diff between 10.43.0 and 10.44.0 on GitHub. The following release notes are directly from the changelog:
v10.44.0
- [10.x] Fix empty request for HTTP connection exception by @driesvints in https://github.com/laravel/framework/pull/49924
- [10.x] Add Collection::select() method by @morrislaptop in https://github.com/laravel/framework/pull/49845
- [10.x] Refactor
getPreviousUrlFromSession
method in UrlGenerator by @milwad-dev in https://github.com/laravel/framework/pull/49944 - [10.x] Add POSIX compliant cleanup to artisan serve by @Tofandel in https://github.com/laravel/framework/pull/49943
- [10.x] Fix infinite loop when global scopes query contains aggregates by @mateusjunges in https://github.com/laravel/framework/pull/49972
- [10.x] Adds PHPUnit 11 as conflict by @nunomaduro in https://github.com/laravel/framework/pull/49957
- Revert "[10.x] fix Before/After validation rules" by @taylorotwell in https://github.com/laravel/framework/pull/50013
- [10.x] Fix the phpdoc for replaceMatches in Str and Stringable helpers by @joke2k in https://github.com/laravel/framework/pull/49990
- [10.x] Added
setAbly()
method forAblyBroadcaster
by @Rijoanul-Shanto in https://github.com/laravel/framework/pull/49981 - [10.x] Fix in appendExceptionToException method exception type check by @t1nkl in https://github.com/laravel/framework/pull/49958
- [10.x] DB command: add sqlcmd -C flag when 'trust_server_certificate' is set by @hulkur in https://github.com/laravel/framework/pull/49952
- Allows Setup and Teardown actions to be reused in alternative TestCase for Laravel by @crynobone in https://github.com/laravel/framework/pull/49973
- [10.x] Add
toBase64()
andfromBase64()
methods to Stringable and Str classes by @mtownsend5512 in https://github.com/laravel/framework/pull/49984 - [10.x] Allows to defer resolving pcntl only if it's available by @crynobone in https://github.com/laravel/framework/pull/50024
- [10.x] Fixes missing
Throwable
import and handle iforiginalExceptionHandler
ororiginalDeprecationHandler
property isn't used by alternative TestCase by @crynobone in https://github.com/laravel/framework/pull/50021 - [10.x] Type hinting for conditional validation rules by @lorenzolosa in https://github.com/laravel/framework/pull/50017
- [10.x] Introduce new
Arr::take()
helper by @ryangjchandler in https://github.com/laravel/framework/pull/50015 - [10.x] Improved Handling of Empty Component Slots with HTML Comments or Line Breaks by @comes in https://github.com/laravel/framework/pull/49966
- [10.x] Introduce Observe attribute for models by @emargareten in https://github.com/laravel/framework/pull/49843
- [10.x] Add ScopedBy attribute for models by @emargareten in https://github.com/laravel/framework/pull/50034
- [10.x] Update reserved names in
GeneratorCommand
by @xurshudyan in https://github.com/laravel/framework/pull/50043 - [10.x] fix Validator::validated get nullable array by @helitik in https://github.com/laravel/framework/pull/50056
- [10.x] Pass Herd specific env variables to "artisan serve" by @mpociot in https://github.com/laravel/framework/pull/50069
- Remove regex case insensitivity modifier in UUID detection to speed it up slightly by @maximal in https://github.com/laravel/framework/pull/50067
- [10.x] HTTP retry method can accept array as first param by @me-shaon in https://github.com/laravel/framework/pull/50064
- [10.x] Fix DB::afterCommit() broken in tests using DatabaseTransactions by @oprypkhantc in https://github.com/laravel/framework/pull/50068