Facades

Facades give a clean, static-like interface to Laravel's services.

A facade is a class that provides a static-looking interface to an underlying service in Laravel's service container. You have already seen them: Str, Arr, Route and DB are all facades.

They let you write short, readable code like Str::upper('hi') instead of resolving the service manually. Behind the scenes the call is forwarded to a real object.

Common facades

  • Illuminate\Support\Str — string helpers.
  • Illuminate\Support\Arr — array helpers.
  • Route, DB, Cache, Auth — framework services.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A controller caches expensive database results by calling Cache::remember() without needing to inject a cache instance through the constructor.
  • A feature test swaps the real Mail facade with Mail::fake() so no actual emails are sent, then asserts that the correct mailable was dispatched.
  • A developer uses Log::channel('slack')->critical() to route fatal errors to a dedicated Slack channel directly from application code.

More examples

Cache data via the Cache facade

Calls the Cache facade to store and retrieve all products for one hour, avoiding repeated database queries.

Example · php
use Illuminate\Support\Facades\Cache;

public function index(): JsonResponse
{
    $products = Cache::remember('products.all', 3600, function () {
        return Product::all();
    });

    return response()->json($products);
}

Fake a facade in a test

Replaces the real mail driver with a fake so tests can assert that a mailable was queued without actually sending email.

Example · php
use Illuminate\Support\Facades\Mail;
use App\Mail\OrderConfirmation;

public function test_order_email_is_sent(): void
{
    Mail::fake();

    $this->post('/orders', $this->orderPayload());

    Mail::assertSent(OrderConfirmation::class);
}

Three ways to reach the same service

Shows three equivalent ways to use the cache service, illustrating that facades are syntactic sugar over the service container.

Example · php
use Illuminate\Support\Facades\Cache;

// 1. Facade static call
$value = Cache::get('key');

// 2. Resolve from container by alias
$value = app('cache')->get('key');

// 3. Constructor injection (preferred for testability)
public function __construct(
    private \Illuminate\Contracts\Cache\Repository $cache
) {}

Discussion

  • Be the first to comment on this lesson.