hulkur / laravel-hasmany-keyby
Add possibility to have related models in many-to-many relationship attached to the parent model by defined key values.
Installs: 35 518
Dependents: 0
Suggesters: 0
Security: 0
Stars: 3
Watchers: 2
Forks: 1
Open Issues: 0
Requires
- php: ^8.2
- illuminate/database: ^11.0
- illuminate/support: ^11.0
Requires (Dev)
- brianium/paratest: ^7.0
- doctrine/persistence: ^2.0
- mockery/mockery: ^1.5
- nunomaduro/collision: ^8.1
- orchestra/testbench: ^9.0
README
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