I am discussing whether I should use Laravel to create an online store.
Demand. Show the cart in the sidebar listing the product in the main area. I need to bind data to my partial views.
I created a PartialController to display partial views.
class PartialController extends BaseController { public function showCartSummary() { $cartItems = Cart::all(); return View::make('partials.cartsummary', array( 'cart' => $cartItems, )); } public function showProducts() { $products = Products::all(); return View::make('partials.products', array( 'products' => $products, )); } }
I created a store index index to pull out partial views
Shop.Index.Blade.php
@extends('master') @section('content') @include('partials.cart') @stop @section('side1') @include('partials.products') @stop
The problem is that no data is passed to these views because partials.cart and partials.products are not called from their own controllers.
My workaround is to query the database in ShopController and pass that to the shop.index .
ShopController.php
I also created ShopController
public function showIndex() { $cartItems = Cart::all(); $products = Product::all(); return View::make('shop.index', array( 'cartItems' => $cartItems, 'products' => $products )); }
Of course, now I repeat my queries on db, and I don't want to repeat the same queries in every controller method that uses multiple views.
What is the best way to do this?
NB: I have more simplified database calls for the purposes of this question, and the code may have one or two typo / syntax errors, but are not important for this question.
Iteration 2:
I found that I can use view composers to create viewmodels / presenters.
shop.blade.php
@extends('master') @section('content') @include('partials.products') @stop @section('side1') @include('partials.cartitems') @stop
Now, to pass data to partial views: First, I turn off PartialController.php, and then change filter.php filters.php
App::before(function($request) { View::composer('partials.products', 'ProductComposer'); View::composer('partials.cartitems', 'CartComposer'); }); class ProductComposer { public function compose($view) { $view->with('products', Product::all()); } } class CartComposer { public function compose($view) { $view->with('cartitems', Cart::all()); } }
It's still very dirty, I don't want to fill in all my partial views in the filters.php file ... Is there a proper / official way to do this? Any examples?