Home > front end >  Access php variable defined in master blade in other blades where master blade is extended . PHP Lar
Access php variable defined in master blade in other blades where master blade is extended . PHP Lar

Time:09-18

I am working on a laravel PHP project and I have a global blade where I have defined a variable

<?php
    $a = "some value fetched dynamically";
?>

And I am extending this blade in over 100 blade files like this

@extends('global')

In all these blades how can I access this $a variable?

Versions - PHP 7.2.34, Laravel 5.3.31

Thanks in advance.

PS: if there is any other way where I can get the PHP variable/function defined in the global blade in other blades please feel free to suggest.

CodePudding user response:

Choose blade or layout you are importing in every blade and add this code

// AppServiceProvider.php

public function register()
{
  // the layout you want, You can add '*' instead of 'blade' for all views
  \View::composer('blade', function ($view) {
     $value = "Data"
     $view->with('value', $value);
  });
}

At the blade use it like a normal variable.


Also, you can do it in another way Laravel composer

  • Related