Skip to content

Add possibility to have related models in many-to-many relationship attached to the parent model by defined key values. ($user->groups => [$group->id => $group])

License

hulkur/laravel-hasmany-keyby

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

33 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Extend Laravel HasMany relationship with KeyBy method

Latest Version on Packagist 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];

This is specially useful in case there is a 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)
    {{optional($user->accesslevels[$group->id])->level}}
  @endforeach
@endforeach

About

Add possibility to have related models in many-to-many relationship attached to the parent model by defined key values. ($user->groups => [$group->id => $group])

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages