Question

I have a question about making some elements available in any view file

Lets say im building a webshop and on every page i will be having my sidebar, shoppingcart, user greeting in the top.

How can i make these things available in all my view files?

I could make a class, lets say class Frontend

I could do something like this:

class Frontend {

    static $me;

    public function get(){
        if(!self::$me){
            self::$me = new self();
        }
        return self::$me;
    }

    private function getShoppingCart(){
        // do things 
    }

    public function getData(){


        return array(
                'Username' => User::find(1)->UserName,
                'Cart' => $this->getShoppingCart()
        );

    }

}

Now in my controller i could pass this Frontend object into the view

View::make('file.view')->with(array('data' => Frontend::get()->getData()));

But this way i will end up with a god class containing way too much stuff and in every controller method i would have to pass these data, which is not relevant to the controller method

Is there a way in Laravel that makes specific data available across all view files?

Thanks!

Was it helpful?

Solution 2

To keep everything clean, every part of the page should be its own *.blade.php file which would be put together using a master template of sorts.

master.blade.php

@yield('includes.sidebar')

@yield('users.greeting')

@yield('store.shoppingcart')

Then you can use view composers so that each time these views are loaded, the data you want is injected into them. I would probably either create a new file which would get autoloaded, or if you have service providers for the separate portions of your app that these views would use, it would also go great in there.

View::composer('users.greeting', function($view)
{
    $view->with('user', Auth::user());
});

In this case, it would make the user model available inside your view. This makes it very easy to manage which data gets injected into your views.

OTHER TIPS

Use share:

View::share('name', 'Steve');

as per http://laravel.com/docs/responses#views

You are close with your 'god class' idea. Setting a $data variable in a basecontroller has helped me with similar issues

class BaseController extends Controller {


protected $data;

public function __construct() {

    $this->data['Username'] =  User::find(1)->UserName
    $this->data['Cart'] = $this->getShoppingCart()
 }
}

class Frontend extends BaseController {

   function someMethod(){
      View::make('file.view', $this->data)
   }
}    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top