I am retrieving the items which have been added to a cart in a session, and also calculating the total number of items. I create an array to which these items are added, which I use to display the cart. I take the number of items in the cart and display that number in every view. I have the code worked out, but as of now the only way to make it work is to copy and paste it in every route. Research suggests using a middleware is the way to share the variables among all views, but I have been unable to get this to work.
First, here is the code for the middleware.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\View;
use App\Models\Item;
class GetCart
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$response = $next($request);
$items = Item::all();
$cartItems = [];
for($i=0; $i < count($items); $i ){
if(null !== Session::get('cartItem'.$i)){
$item = Session::get('cartItem'.$i);
array_push($cartItems, $item);
}
};
$totalNum = 0;
for($i=0; $i < count($cartItems); $i ){
if(isset($cartItems[$i])){
$totalNum = $cartItems[$i]['quantity'];
}
}
View::share('cartItems', $cartItems);
View::share('totalNum', $totalNum);
return $response;
}
}
In App\Http\Kernel.php, I add it to the $middleware variable, which makes it automatically load at every request.
protected $middleware = [
\App\Http\Middleware\GetCart::class
];
However, I am still not able to retrieve the variable. It says 'undefined variable.' So I would appreciate help on what I am missing, as to why I am not able to share this variable among all views. As I said, I can make it work by copying and pasting the code into every route, but I know this is not the proper way.
CodePudding user response:
The issue here is that you already working with the response in your middleware. See https://laravel.com/docs/8.x/middleware#middleware-and-responses You need it before passing deeper into the application. Then should be available in all views.
But I think it would be better to make a separate blade for the cart (cart.blade.php) and include it in all other views where it is needed. Then make a new view composer class for that cart view and share your cartItems
and totalNum
in it.
See https://laravel.com/docs/8.x/views#view-composers