Reputation: 100
$cartItems
contains all the rows of products from database and I am using this inside a blade file.
I want to pass this $cartItems
back to a controller from this blade file
Note: $cartItems
is from index()
function in a controller like below.
$cartItems = DB::table('products')->whereIn('id', $cartItemsArray)->get();
return view('cart.index', compact('cartItems')
Below is my code.
index.blade.php
<a href="{{route('cart.checkout',$cartItems)}}" class="site-btn">Proceed to checkout</a>
web.php
Route::get('/cart/checkout/{cartItems}', 'CartController@checkout')->name('cart.checkout')->middleware('auth');
CartController.php
public function checkout($cartItems)
{
dd($cartItems);
return view('cart.checkout');
}
The error I am getting is,
Missing required parameters for [Route: cart.checkout] [URI: cart/checkout/{cartItems}]. (View: E:\github\LARAVEL\Deal-Ocean\resources\views\cart\index.blade.php)
Upvotes: 1
Views: 4618
Reputation: 5124
You can use a form to send data back to server
Update your route from get
to post
Route::post('/cart/checkout', 'CartController@checkout')->name('cart.checkout')->middleware('auth');
Use a form to post data to server. You can pass any additional data along with the request as well.
<form method="post" action="/cart/checkout">
@foreach($cartItems as $item)
<input name="cartItems[]" value="{{ $item->id }}"
@endforeach
<button class="site-btn">Proceed to checkout</button>
</form>
And in your controller use Request
to access data
public function checkout(Request $request)
{
$cartItems = DB::table('products')->whereIn('id', $request->get($cartItems))->get();
dd($cartItems);
return view('cart.checkout');
}
If you want to proceed with the get request you should be able to do as follow
As $cartItems
is a collection of products. So you can send the product ids and query the products using the ids from request.
<a href="{{ route('cart.checkout', ['cartItems' => $cartItems->pluck('id')->toArray()]) }}"
class="site-btn">Proceed to checkout</a>
Update controller
public function checkout(Request $request)
{
$cartItems = DB::table('products')->whereIn('id', $request->get($cartItems))->get();
dd($cartItems);
return view('cart.checkout');
}
Upvotes: 3
Reputation: 89
Why use the same code logic of the index() method in the checkout method in the CartController.
the checkout method will look like this:
$cartItems = DB::table('products')->whereIn('id', $cartItemsArray)->get();
return view('cart.checkout', compact('cartItems');
Upvotes: 0