0

The question title is confusing I know, cannot put better way to describe my situation... I have quite some routes for ecommerce website, and I'm using blade templating system so that there is a header.blade.php that is being used for all my page of this site. In the header, there's a shopping cart icon, when hovers on it, all the products that are in the shopping cart for the current user would show up. Problem is with all the routes that goes to some page that contains this header template, I have to add

$shopping_cart_info = ProductController::getShoppingCartInfo();
return View::make('somePageView')->with('shopping_cart_info', $shopping_cart_info); 

for each and every one of them in the corresponding controller function, and there are more than 50 routes that require to do so... Is there a way to group these routes to let them all have the $shopping_cart_info so that I don't have to add it one by one?

1 Answer 1

1

Sure thing, except you don't do it in the routes. It's called a view composer, and it works like this:

// adds shopping cart info to the view
View::composer(['some.view.1', 'some.view.2'], function($view){
    $shopping_cart_info = ProductController::getShoppingCartInfo();
    $view->with('shopping_cart_info', $shopping_cart_info);
});

Now, the views "some.view.1" and "some.view.2" will both contain the shopping cart info variable. You can have as many views as you'd like there. In your case, it sounds like you have one view which uses it but which is called from loads of places. View composers were created just for that sort of thing! :)

For a smaller project, I typically create a file app/composers.php and autoload it from the app/global.php file like so: require app_path().'/composers.php';

Documentation: http://laravel.com/docs/4.2/responses#view-composers

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, that's the one, should've read the documentation more careful, thanks bro!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.