What are Facades in Laravel
Facades in Laravel provide a static-like interface to classes that are actually resolved from Laravel’s Service Container.🔹 Simple Idea
Facades look like static calls, but behind the scenes they use Dependency Injection.
Example:
use Illuminate\Support\Facades\Cache;
Cache::put('key', 'value', 600);
👉 Cache looks static, but Laravel is actually resolving it from the container.
🔹 What Problem Do Facades Solve?
Without Facades ❌:
class UserController {
protected $cache;
public function __construct(CacheManager $cache) {
$this->cache = $cache;
}
public function index() {
$this->cache->put('key', 'value', 600);
}
}
With Facades ✅:
use Illuminate\Support\Facades\Cache;
Cache::put('key', 'value', 600);
👉 Cleaner and shorter code.
🔹 How Facades Work Internally
-
You call a Facade (e.g.,
Cache::put()) - Laravel maps it to a service container binding
- The actual class instance is resolved
- Method is executed
🔹 Common Laravel Facades
-
Cache→ caching system -
DB→ database queries -
Auth→ authentication -
Route→ routing -
Log→ logging
Example:
use Illuminate\Support\Facades\DB;
$users = DB::table('users')->get();
🔹 Facade vs Dependency Injection
| Facade | Dependency Injection |
|---|---|
| Static-like syntax | Uses constructor/method |
| Quick & simple | More flexible |
| Harder to test (without mocking) | Easier to test |
| Less boilerplate | More explicit |
🔹 Are Facades Really Static?
❌ No
They are just syntactic sugar over Laravel’s service container.
🔹 When to Use Facades
✅ Use when:
- You want quick, readable code
- Small to medium logic
- Prototyping
⚠️ Avoid when:
- Writing large, testable applications
- Need flexibility or multiple implementations
🔹 Example (Real Use)
use Illuminate\Support\Facades\Log;
Log::info('User logged in');