Looking to hire Laravel developers? Try LaraJobs

laravel-when-on-relation maintained by mashirou1234

Description
Adds conditional callbacks on Laravel Eloquent relationship instances.
Last update
2026/05/31 05:11 (dev-main)
License
Downloads
2

Comments
comments powered by Disqus

Laravel When On Relation

Latest Version on Packagist Tests License

This package adds a whenOnRelation() macro to Eloquent relationship instances.

Installation

composer require mashirou1234/laravel-when-on-relation

The service provider is registered automatically by Laravel package discovery.

Usage

It is intended for cases where a conditional callback needs the relationship instance itself:

use Illuminate\Database\Eloquent\Relations\BelongsToMany;

$user->posts()
    ->whenOnRelation($condition, function (BelongsToMany $relation) {
        return $relation->wherePivotIn('post_id', [1, 2]);
    });

The callback receives the relationship instance and the resolved condition value:

$user->posts()
    ->whenOnRelation($roleId, function (BelongsToMany $relation, int $roleId) {
        return $relation->wherePivot('role_id', $roleId);
    });

This package does not add a query builder method that accepts a relationship name:

// Not supported:
User::query()->whenOnRelation('posts', ...);

Why

Calling when() on an Eloquent relationship is forwarded to the underlying Eloquent builder. That keeps existing callbacks working, but it means the callback receives an Illuminate\Database\Eloquent\Builder instead of the relationship instance.

whenOnRelation() leaves the existing when() behavior unchanged and provides an opt-in helper for relation-specific methods such as wherePivotIn().

Requirements

  • PHP 8.3 or higher
  • Laravel 13.x / Illuminate 13.x

Testing

composer test

Run composer lint to check formatting.

Please see CONTRIBUTING.md before proposing behavior changes. Security reporting is covered in SECURITY.md.

License

The MIT License (MIT).