Looking to hire Laravel developers? Try LaraJobs
This package is not available.

laravel-hasmany-keyby maintained by hulkur

Description
Add possibility to have related models in many-to-many relationship attached to the parent model by defined key values.
Author
Last update
2026/11/20 22:09 (dev-master)
License
Downloads
88 587

Comments
comments powered by Disqus

Extend Laravel HasMany relationship with KeyBy method

Latest Version on Packagist Laravel Compatibility GitHub Workflow Status Total Downloads

Adds possibility to have related models in many-to-many relationship attached to the parent model by defined key values. Usually it would be related model id.

call:

$users = User::with('groups')->all()

laravel default:

$user->groups = [0 => $group];

New usage with keyBy:

class User extends Model
{
  use HasManyKeyByRelationship;

  public function groups()
  {
    return $this->hasMany(Group::class)->keyBy('id'); // can be string or callable
  }
}

result:

$user->groups = [$group->id => $group];

Some real life use cases

  1. When you need to target order items by product id to apply order discounts.

    • Ex: discount for specific product on order total/shipping method etc
  2. When you need to manipulate pivot records in mass.

    • Ex: users/groups grid where grid fields are some value in pivot record and not all pivot records exist
@foreach($users as $user)
  @foreach($groups as $group)
    {{$user->accesslevels[$group->id]?->level}}
  @endforeach
@endforeach