Home >Backend Development >PHP Tutorial >How Can I Share Data Across All Views in Laravel 5?
Passing Data to All Views in Laravel 5
In Laravel 5, sharing data among all views can be achieved through various methods.
Method 1: Using BaseController
Create a BaseController class that extends Laravel's Controller.
class BaseController extends Controller { public function __construct() { $data = [1, 2, 3]; View::share('data', $data); } }
All other controllers should then extend from BaseController:
class SomeController extends BaseController { // ... }
Method 2: Using Filter
Create a filter in app/filters.php or in a separate filter class file:
App::before(function($request) { View::share('data', [1, 2, 3]); });
Alternatively, define a custom filter:
Route::filter('data-filter', function() { View::share('data', [1, 2, 3]); });
Apply the filter to specific routes using Route::filter().
Method 3: Using Middleware
Pass data using middleware to views:
Route::group(['middleware' => 'SomeMiddleware'], function() { // Routes }); class SomeMiddleware { public function handle($request) { View::share('data', [1, 2, 3]); } }
Method 4: Using View Composer
Bind data to views using View Composer. This allows you to bind data to specific views or all views.
To bind data to a specific view, create a ViewComposer class and register it in the service provider:
// ViewComposer use Illuminate\Contracts\View\View; class DataComposer { public function compose(View $view) { $view->with('data', [1, 2, 3]); } } // Service Provider public function boot() { view()->composer('view-name', 'DataComposer'); }
To bind data to all views, use the following code in the service provider:
view()->composer('*', 'DataComposer');
Reference:
The above is the detailed content of How Can I Share Data Across All Views in Laravel 5?. For more information, please follow other related articles on the PHP Chinese website!