I've solved my issue by creating a class that deals specifically with that cart Cookie generation and making it a singleton class that's injected into the service container.
Once it generates a unique cart id, it will store it so I can access it later in the same request with app(CartCookie::class)->id()
. If anyone can think of a better way that's still clean then by all means let me know.
Here's the code:
CartCookie.php
namespace App\Services;
use App\Cart;
use Illuminate\Http\Request;
class CartCookie
{
private $id;
private $request;
function __construct(Request $request)
{
$this->request = $request;
if ($request->cookie('cart_id')) {
$this->id = $request->cookie('cart_id');
} else {
$this->id = $this->generateUniqueCartId();
}
}
public function id()
{
return $this->id;
}
private function generateUniqueCartId()
{
do {
$id = md5(time() . 'cart' . rand(100000000000000, 9999999999999999));
} while (Cart::find($id));
return $id;
}
}
CartCookieServiceProvider.php
namespace App\Providers;
use App\Services\CartCookie;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
class CartCookieServiceProvider extends ServiceProvider
{
public function boot(Request $request)
{
$this->app->singleton(CartCookie::class, function ($app) use ($request) {
return new CartCookie($request);
});
}
}
CartCookieMiddleware.php
namespace App\Http\Middleware;
use App\Cart;
use Closure;
class CartCookie
{
public function handle($request, Closure $next)
{
if (!$request->cookie('cart_id')) {
$id = app(\App\Services\CartCookie::class)->id();
return $next($request)->withCookie(cookie()->forever('cart_id', $id));
}
return $next($request);
}
}