php - Use Eloquent scope on each eager loaded element in Laravel -
i have situation this. there authors
, books
. books
belong authors
, authors
have many books
. there table publish_year
different years have primary keys
cast against them. i.e. year 2005 has primary key 1, year 2006 has primary key 2 etc.
now, on books table, year_id
foreign key
refers primary key
of publish_year
table. want eager load authors
books
specific year (which made active admin panel).
i have developed following eloquent query. models author
, book
, publishyear
. there additional where
conditions performed on query
.
return author::with(['books' => function($query) { $query->where('year_id', '=', publishyear::where('is_active', '=', 1)->pluck('id')) ->where('is_available', '=', 't') ....; }])->get();
it works. there way use scope inside query this:
return author::with(['books' => function($query) { $query->scope(); }
so, can abstract away implementation detail controller.
we use repository design pattern this.
the repository mediates between data source layer , business layers of application. queries data source data, maps data data source business entity, , persists changes in business entity data source. repository separates business logic interactions underlying data source or web service.
laravel has great support repository design using interfaces. in our current webhosting control panel it's used facilitate our complex data structures multiple relations.
ryan tablada has nice article describing exact benefits: http://ryantablada.com/post/two-design-patterns-that-will-make-your-applications-better
if need more code examples see heera.it article goes more detail how implement it: http://heera.it/laravel-repository-pattern