Using the Laravel context() Helper for Managing Application Context Data
The article introduces Laravel's new context() helper, demonstrating its basic usage and a real‑world multi‑tenant example, showing how to add, retrieve, and default context values and simplify shared data handling throughout the request lifecycle.
Easily manage context data in a Laravel application? The new context() helper function offers an elegant solution for handling context information throughout the application lifecycle.
Basic Usage
The context() helper provides several basic usages:
// 将数据添加到上下文
context(['user' => auth()->user()]);
// 获取整个上下文对象
$context = context();
// 获取特定值
$user = context('user');
// 使用默认后备获取
$theme = context('theme', 'light');Real Example
Below is an example of using the context() function in a multi‑tenant application:
class TenantMiddleware
{
public function handle($request, $next)
{
$tenant = Tenant::fromDomain($request->getHost());
context([
'tenant' => $tenant,
'tenant_settings' => $tenant->settings,
'tenant_features' => $tenant->activeFeatures
]);
return $next($request);
}
}
class OrderController extends Controller
{
public function store(OrderRequest $request)
{
$tenant = context('tenant');
$features = context('tenant_features', []);
if (in_array('advanced_ordering', $features)) {
return $this->handleAdvancedOrder($request);
}
// 常规订单处理
$order = Order::create([
'tenant_id' => $tenant->id,
'user_id' => auth()->id(),
'items' => $request->items
]);
return response()->json([
'order' => $order,
'settings' => context('tenant_settings')
]);
}
}The context() helper function makes it convenient to maintain and access shared data during the request lifecycle.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
