I am debating whether I should use Laravel to build an online store.
Requirement - Show a shopping cart in sidebar with product listing in main area. i need to bind data to my partial views.
I have 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 have created a shop index view to pull in the 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 on to these views because partials.cart and partials.products are not being called from their own controllers.
My workaround involves querying the database within the ShopController and passing this to the shop.index view.
ShopController.php
I have also created a ShopController
public function showIndex()
{
$cartItems = Cart::all();
$products = Product::all();
return View::make('shop.index', array(
'cartItems' => $cartItems,
'products' => $products
));
}
Of course, I am now repeating my db queries and I don't want to have to repeat the same queries in every controller method where multiple views are used.
What is the best way of doing this?
NB: I have over simplified database calls for the purposes of this question & there may be one or two typos / syntax errors in code, but not important for this question.
Iteration 2:
I have 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 the data to the partial views: Firstly I ditch the PartialController.php, then amend filters.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());
}
}
This is still very messy, i don't want to stuff all my partial views into the filters.php file... Is there a proper / official way of doing this? Any examples?