Back to Blog

Chaperone Eloquent Models in Laravel 11.22

Julian Beaujardin
Julian Beaujardin September 5th, 2024

The Laravel team released v11.22 this week, with the chaperone() Eloquent method for inverse relations, support for passing backed Enums to Queuable methods, the ability to pass backed Enums to route ->name() and ->domain() methods, and more.

Chaperone Eloquent Relations

Samuel Levy contributed the Eloquent inverse/chaperone model relation that Taylor demonstrated in his 2024 Larcon US keynote during the open-source part of the talk.

public function comments(): HasMany
{
    return $this->hasMany(Comment::class)->chaperone('post');
}

The chaperone()/inverse() method avoids unexpected N+1 queries by linking back to the parent after the relationship query has run. The above relationship will link the appropriate Post model in the correct relation on Comment instances (with scopes intact).

See Pull Request #51582 for more details.

Support Backed Enum in the Queueable Trait

Seth Phat contributed support for BackedEnum in Queuable trait methods:

  • onQueue()
  • onConnection()
  • allOnQueue()
  • allOnConnection()

Here's an example from the pull request:

use App\Enums\QueueConnection;
use App\Enums\QueueName;

// Before
public function register()
{
    $user = User::create([...]);

    SendWelcomeEmailJob::dispatch($user)
        ->withConnection(QueueConnection::REDIS->value)
        ->onQueue(QueueName::HIGH->value);
}

// After
public function register()
{
    $user = User::create([...]);

    SendWelcomeEmailJob::dispatch($user)
        ->withConnection(QueueConnection::REDIS)
        ->onQueue(QueueName::HIGH);
}

Allow Enums to be Passed to Routes

@NickSdot contributed passing BackedEnum to Route domain() and name() methods:

// Before
Route::domain(InterfaceDomain::Marketing->value)
    ->name(Routes::Home->value)
    ->get('/contact', ContactController::class);

// After
Route::domain(InterfaceDomain::Marketing)
    ->name(Routes::Home)
    ->get('/'contact, ContactController::class);

Release notes

You can see the complete list of new features and updates below and the diff between 11.21.0 and 11.22.0 on GitHub. The following release notes are directly from the changelog: