Laravel Facades & Helpers
February 12, 2024
•
12 min read
Introduction
Laravel facades provide a static interface to services in the container. Helper functions are global functions that make common tasks easier. Understanding both helps you write cleaner Laravel code.
How Facades Work
Facades use PHP magic methods to proxy calls to services in the container:
// This facade call:
Cache::put('key', 'value', 3600);
// Is actually resolved to:
app('cache')->put('key', 'value', 3600);
// The facade class looks like:
class Cache extends Facade
{
protected static function getFacadeAccessor()
{
return 'cache';
}
}
Common Facades
// Authentication
Auth::user()
Auth::check()
Auth::login($user)
// Cache
Cache::get('key')
Cache::put('key', 'value', $minutes)
Cache::remember('key', $minutes, fn() => $data)
// Database
DB::table('users')->get()
DB::transaction(fn() => ...)
// Log
Log::info('message')
Log::error('error', ['context' => $data])
// Request
request('key')
Request::input('key')
// Route
Route::get('/path', $controller)
Route::post('/path', $controller)
Helper Functions
// Array helpers
array_get($array, 'key.nested', 'default')
array_first($array)
array_pluck($array, 'key')
// String helpers
str_limit($string, 100)
str_slug($string)
trans('messages.welcome')
// Path helpers
resource_path('views')
storage_path('app')
base_path()
// Other helpers
view('emails.user')
config('app.timezone')
redirect('/home')
back()
old('email')
csrf_token()
__($text)
Creating Custom Facades
// 1. Create service class
class PaymentService
{
public function process($amount)
{
// Payment logic
}
}
// 2. Register in service provider
$this->app->singleton('payment', fn() => new PaymentService());
// 3. Create facade
class Payment extends Facade
{
protected static function getFacadeAccessor()
{
return 'payment';
}
}
// 4. Add to autoload in composer.json
"files": ["app/Support/Facades/Payment.php"]
Summary
Facades and helpers are powerful tools that make Laravel code more readable. Use them appropriately and understand their underlying implementations for better coding.
For more Laravel tutorials, see Service Container.