1

I have a view composer that I'm using to calculate all the variables that go in the shopping basket (which is a partial that I include a lot) of the app I'm creating. It is essentially a much more complex version of this:

public function compose($view)
{
    $giftbox_total_pre = Giftbox::getTotal();
    $giftbox_items_total = number_format($giftbox_total_pre, 2);

    $view->with(compact(
        'giftbox_items_total',
    ));
}

Then in my routes I have:

View::composer(['layouts.bag', 'shop.basket', 'giftbox.basket'], 'Acme\Composers\BasketComposer');

But, I'm just adding Ajax to my app, and it would be good if after a request I could grab the variables from the View Composer. Is there a way of doing that? Or is the composer the wrong thing to be using in this instance?

For example, to add an item without Ajax, I have a controller function like the following route:

Route::post('/cart/add/{type?}/{quantity?}', 'CartsController@addToCart');

And controller:

public function addToCart($type='subscription', $quantity=1)
{
    $product = Product::find(Input::get('id'));
    $price = $product->box_price;

    Cart::insert([
        'id' => $type . $product->id,
        'table_id' => $product->id,
        'name' => $product->name,
        'price' => $price,
        'quantity' => $quantity,
        'cart_type' => $type,
    ]);

    return Redirect::back()->with('success', 'Added to cart!');
}

First, proper, Laravel project so I may have myself in a bit of a mess! I can Ajax submit to the route and it works fine, but I just can't work out how to get back a decent JSON array of the cart.

2
  • So the response should be the whole cart plus giftbox_items_total like you have it in the view composer as JSON? Commented Dec 31, 2014 at 13:20
  • Yes, but how do I access variables made inside a view composer? Commented Dec 31, 2014 at 13:24

2 Answers 2

2

View composers are nice, but they are for views. And when you return JSON you don't use views but

return Response::json($data);

This means no view will be rendered. I you move all the logic from the composer inside a function on the model. (It looks like you sort of already that with Giftbox::getTotal())

And then just call that method in the controller

$giftbox_items_total = Giftbox::getTotal();
Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, I think I got a little mixed up with my view composers. I've moved the whole function into the model like you said, then in my composer I just set up a $cart = CartModel::get() and then just carry on as before with $view->with($cart);. Thanks!
-1
return Response::json(['html' => (string)View::make('cart.widget')]);

Comments

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.