Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

With Laravel 10.44 you can add Model Scopes and Observers using PHP Attributes

Last updated on by

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

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article