Laravel: how to pass a variable to my main layout

I am trying to pass a variable to my main layout. This is because I need it on all pages. I thought there was something like this on my BaseController

protected function setupLayout()
{
    if ( ! is_null($this->layout))
    {
        $footertext = MyText::where('status', 1);
        $this->layout = View::make($this->layout, ['footertext' =>$footertext ]);
        }
    }
}

      

And on mine I thought that writing something like this on my main.blade.php might work.

 {{ $footertext }}.

      

Instead, I have this error,

Undefined variable: footertext

and after two hours of inspection ... I couldn't find a solution. Any help is appreciated.

+3


source to share


3 answers


Not too long ago I tried to do the same.

If you are using Laravel 5 you can edit AppServiceProvider.php internally app/Providers

and register a provider for this layout like:

public function boot()
{
  view()->composer('my.layout', function($view) {
    $myvar = 'test';
    $view->with('data', array('myvar' => $myvar));
  });
}

      

Now if you are using Laravel 4 I think it is easier. In app/filters.php

:



View::composer('my.layout', function ($view) {
  $view->with('variable', $variable);
});

      

In both cases, any variable you pass will be available to all templates that extend the main template.

Links:

https://laracasts.com/discuss/channels/general-discussion/laravel-5-pass-variables-to-master-template https://coderwall.com/p/kqxdug/share-a-variable-across-views -in-laravel? p = 1 & q = author% 3Aeuantor

+2


source


For laravel 5.3 I am using AppServiceProvider.php

internallyapp/Providers

public function boot()
{
    view()->composer('layouts.master', function($view)
    {
        $view->with('variable', 'myvariable');
    });
}

      



Link: https://laracasts.com/discuss/channels/general-discussion/laravel-5-pass-variables-to-master-template

* Dedicated class

+1


source


Sometimes we need to pass data from a controller to view in laravel, for example when working with a database query, selecting an option, etc. its simple and lightweight with built in function in laravel. We can send data from controller to view using () in laravel. There are also more ways to send or transmit data for viewing from the controller. I am describing a simple way to pass a form data controller to view in laravel.

1. Passing an array:

$data = array(
    'name'  => 'Rakesh',
    'email' => 'sharmarakesh395@gmail.com'
);

return View::make('user')->with($data);

//Accesing $data on view :-

{{$data}}
{{$data['email']}}

      

2. Working with a request:

function view() {
  $q = Model::where('name', '=', 'Foo')->first(); 
  $users = Model::order_by('list_order', 'ASC')->get();
  return $view->with('users', $users)->with('q', $q);
}
//Accesing on view :-
{{ $q->name }}

      

Hope it helps you :)

0


source







All Articles