Laravel interview question · Most asked
How do facades work, and when would you prefer dependency injection instead?
Summary
A facade is a class with static-looking methods that forwards each call to an object resolved from the service container. Cache::get() is really app('cache')->get().
Longer Answer
Each facade defines getFacadeAccessor(), the container key of the underlying service. The base Facade class implements __callStatic, resolves that service (and caches the instance) and forwards the call. So facades are not static classes: they are a short syntax for container lookups, and they can be faked in tests (Cache::shouldReceive(...), Mail::fake()).
Prefer constructor injection when a class depends on many services (the constructor documents the dependencies and shows when a class is doing too much), for code shared outside Laravel, and for domain classes that should not know about the framework. Facades are fine, and idiomatic, in controllers, jobs and glue code.
Real-time facades (use Facades\App\Services\Pricing;) turn any class into a facade, which is convenient but hides dependencies.
Key Points
- Facades proxy to container services via
__callStatic. - They are mockable (
fake(),shouldReceive). - Injection makes dependencies explicit; prefer it in domain code.
Explanation
What interviewers look for
The candidate knows facades are not static and are testable, and can argue when explicit injection is clearer.
Follow-up questions
- How would you fake a facade in a test?
- What is the downside of real-time facades?
More most-asked Laravel questions
- How do you validate requests in Laravel? Why use Form Requests?
- Gates or policies: how does authorization work in Laravel?
- How do database transactions work in Laravel, and what pitfalls should you know?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- What is the service container, and how does dependency injection work in Laravel?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- How do queues work in Laravel?