
Eager Loading Without Eloquent: Laravel Collection hasMany
import Tabs from ' @theme /Tabs'; import TabItem from ' @theme /TabItem'; I had two collections of plain arrays and needed to associate them relationally, but I was not working with Eloquent models. Laravel's Collection class is powerful, but it has no built-in way to express a one-to-many relationship between two arbitrary datasets. I built laravel-collection-has-many to fix that. What It Is laravel-collection-has-many is a small PHP library that registers a hasMany() macro on Laravel's Collection class. It lets you attach a related collection to a parent collection using foreign key and local key fields, exactly like Eloquent's eager loading, but for plain data. After calling $users->hasMany($posts, 'user_id', 'id', 'posts') , each user in the collection gains a posts property containing their matched items. flowchart LR A[Parent Collection\nusers] --> B[hasMany Macro] C[Related Collection\nposts] --> B B --> D[Group Related by Foreign Key\nO(n+m) single pass] D --> E[Attach to Paren
Continue reading on Dev.to
Opens in a new tab

