I'm new to Laravel and Web Development in general.
I have an Add to cart
button in shop.blade.php
:
<a href="{{url('cart')}}" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
Then in web.php
I have:
Route::get('cart', function()
{
return View::make('pages.cart', ['active'=>'navCart']);
});
The button obviously redirects to the cart page when pressed.
I'm using LaravelShoppingcart to add items to my cart. To add an item I can use code like:
Cart::add('192ao12', 'Product 1', 1, 9.99);
What I actually want, I think, is some functions, presumably in a Controller (should this be injected into the View?), that I can call from buttons such as Add to cart
, decrement "-" or increment "+".
Putting the Cart::add
in the Route as shown below is clearly wrong but actually achieves half of what I want - the product is added to the cart (I don't actually want that button to move to the cart page).
Route::get('cart', function()
{
Cart::add('192ao12', 'Product 1', 1, 9.99);
return View::make('pages.cart', ['active'=>'navCart']);
});
So, I'm thinking I should be calling methods in the Controller
from the View but everyone says I shouldn't do this so what is the proper way to make the View, namely a button, affect the model in Laravel
?
Just Define a controller
say CartController
and in that create function addToCart()
and then write the code whatever you want.
like,
class CartController extends Controller
{
public function addToCart()
{
//Your cart related logic
Cart::add('192ao12', 'Product 1', 1, 9.99);
return View::make('pages.cart', ['active'=>'navCart']);
}
}
and then define it in your routes/web.php
like,
Route::get('cart', 'CartController@addToCart');