arindam/blade-variable
Declare and use variables directly in Laravel Blade templates with a simple @var directive. Install via Composer (supports auto-discovery; provider available if needed) and set values like @var('name','Arindam') to access as $name in views.
Installation
composer require arindam/blade-variable
Publish the config (if needed):
php artisan vendor:publish --provider="ArindamRoy\BladeVariable\BladeVariableServiceProvider"
First Use Case Define a variable in a Blade template:
@variable('user', ['name' => 'John Doe', 'email' => 'john@example.com'])
Access it later in the same template:
<p>Hello, {{ $user['name'] }}!</p>
Where to Look First
@variable and @endvariable syntax.BladeVariableServiceProvider registers the directive.config/blade-variable.php (if published) for global defaults.Define and Use in a Single Template
@variable('config', ['theme' => 'dark', 'layout' => 'sidebar'])
<div class="{{ $config['theme'] }}">
@include('partials.header', ['layout' => $config['layout']])
</div>
Pass Variables to Included Views
@variable('sharedData', ['title' => 'Dashboard', 'items' => []])
@include('layouts.app')
Access in layouts/app.blade.php:
<h1>{{ $sharedData['title'] }}</h1>
Dynamic Variable Assignment Use PHP logic to conditionally define variables:
@php
$isAdmin = auth()->user()->isAdmin();
@endphp
@variable('permissions', $isAdmin ? ['create', 'edit', 'delete'] : ['view'])
Integration with Blade Components Define variables in a component’s view:
<x-user-card>
@variable('user', $userData)
</x-user-card>
Access in the component’s template:
<p>{{ $user['name'] }}</p>
Scope Limitation
@variable are template-scoped and not available in parent/child templates unless explicitly passed.@include or @stack/@push for shared data.Overwriting Global Variables
$errors), the Blade directive may not work as expected.['app_data' => [...]]).No Direct Access in Controllers
return view('view.name', ['user' => $user]);
Caching Quirks
php artisan view:cache), redefine variables in cached views may not persist.@variable in cached views or clear cache after changes.Type Safety
Use PHP’s json_encode to validate variable structure:
@variable('user', json_decode('{"name":"John"}', true))
Default Values
Set defaults in the config file (config/blade-variable.php) for reusable variables:
'defaults' => [
'app' => ['name' => 'MyApp', 'version' => '1.0'],
],
Access via @variable('app').
Extending Functionality
Override the directive logic by binding a new instance of BladeVariableManager in the service provider:
$this->app->singleton('blade-variable', function () {
return new \ArindamRoy\BladeVariable\BladeVariableManager(['custom' => 'value']);
});
Debugging Dump variables to check their contents:
@variable('debug', ['data' => $someData])
@dump($debug)
Performance For large templates, define variables late (close to where they’re used) to avoid unnecessary scope pollution.
How can I help you explore Laravel packages today?