Question

I have a main layout in views/layouts/main.blade.php How do I pass a variable that is in my ListingsController.php

public function getMain() {
        $uname = Auth::user()->firstname;
        $this->layout->content = View::make('listings/main')->with('name', $uname);
 }

and then I add this to my main.blade.php that is in listings/main

@if(!Auth::check()) 
<h2>Hello, {{ $name }}</h2>
@endif

It works but I cannot pass that variable to the mmaster layout in views/layouts/main.blade.php I simply need to display user's firstname in the header.

Was it helpful?

Solution

It should work the way it its, but... If you need to spread something to more than one view, you better use View::composer() or View::share():

View::share('name', Auth::user()->firstname);

If you need it only on your layout.main, you can:

View::composer('layouts.main', function($view)
{
    $view->with('name', Auth::check() ? Auth::user()->firstname : '');
});

If you need it on all your views you can:

View::composer('*', function($view)
{
    $view->with('name', Auth::check() ? Auth::user()->firstname : '');
});

You can even create a file for this purpose, something like app/composers.php and load it in your app/start/global.php:

require app_path().'/composers.php';

OTHER TIPS

For this use a dedicated class.

First:

// app/Providers/AppServiceProvider.php
public function boot()
{
    view()->composer('layouts.master', 'App\Http\Composers\MasterComposer');
}

And then:

// app/Http/Composers/MasterComposer.php
use Illuminate\Contracts\View\View;

class MasterComposer {

    public function compose(View $view)
    {
        $view->with('variable', 'myvariable');
    }
}

Remember to register service provider.

More: https://laracasts.com/series/laravel-5-fundamentals/episodes/25

$this->data['uname'] = 'some_username';
return View::make('dashboard.home', $this->data);

Edit:: example:

<?php 
class BaseController extends Controller {

    /**
     * Setup the layout used by the controller.
     *
     * @return void
     */
        protected $layout = 'layouts.front';

    protected function setupLayout()
    {
        if ( ! is_null($this->layout))
        {
               $this->data['sidewide_var'] = 'This will be shown on every page';
           $this->layout = View::make($this->layout, $this->data);
        }
    }

}

_

<?php 
class BlogController extends BaseController {
    public function getPost($id)
    {
      $this->data['title'] = 'Post title'; //this will exist on only this page, but can be used in layouts/front.blade.php (for example)
      return View::make('blog.single_post', $this->data);
    }
}

this is the way I am using controllers. Both $sidewide_var and $title can be used in layout or view

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top