Senior LevelLaravel
How do you extend Eloquent by creating custom Builder and Collection subclasses?
❓ Interview Prompt: Explain extending Eloquent Model methods: newEloquentBuilder() for custom query builders, and newCollection() for custom collection methods.
Moving complex query logic out of controllers and models into custom Builder and Collection classes cleanly encapsulates domain logic:
Implementation:
•
Custom Builder: Override 'newEloquentBuilder($query)' on model to return 'UserBuilder' with domain methods ('->whereActiveAdmins()').
•
Custom Collection: Override 'newCollection(array $models)' to return 'UserCollection' with domain methods ('->totalRevenue()').
Code Implementation Example
php
<?php
namespace AppBuilders;
use IlluminateDatabaseEloquentBuilder;
class UserBuilder extends Builder
{
public function whereActiveAdmins(): self {
return $this->where('is_active', true)->where('role', 'admin');
}
}
// Usage in Model:
public function newEloquentBuilder($query): UserBuilder {
return new UserBuilder($query);
}💡Custom Eloquent Builder subclass encapsulating domain query logic.
🎯 Interview Key Takeaway
Override newEloquentBuilder() and newCollection() to encapsulate domain-specific database queries and collection operations.
#Eloquent Builder#Custom Collections#Domain Logic#Senior
Back to all Laravel Questions→