You can try returning after the cookies were sent:
public function addToCart($pid, $qty)
{
if (isset($_COOKIE["shopping_cart_panorama"])) {
$cookie_data = stripslashes($_COOKIE["shopping_cart_panorama"]);
$cart_data = json_decode($cookie_data, true);
} else {
$cart_data = array();
}
$item_id_list = array_column($cart_data, 'item_id');
$wasAdded = false;
if (in_array($pid, $item_id_list)) {
foreach ($cart_data as $keys => $values) {
if ($cart_data[$keys]["item_id"] == $pid) {
$cart_data[$keys]["item_qty"] = $cart_data[$keys]["item_qty"] + $qty;
}
}
} else {
$item_array = array(
'item_id' => $pid,
'item_qty' => $qty,
);
$cart_data[] = $item_array;
$wasAdded = true; // replacing "echo 1;"
}
$item_data = json_encode($cart_data);
setcookie('shopping_cart_panorama', $item_data, time() + (3600 * 24 * 30), "/");
if ($wasAdded) {
echo 1;
}
}
Is this function a controller's method? I would try using Laravel's built in methods for cookie and response manipulation:
public function addToCart($pid, $qty)
{
// request() is a Laravel helper that wraps around super globals
// and let you perform several request related tasks
if (request()->hasCookie('shopping_cart_panorama')) {
$cookie_data = stripslashes(request()->cookie('shopping_cart_panorama'));
$cart_data = json_decode($cookie_data, true);
} else {
$cart_data = [];
}
$item_id_list = array_column($cart_data, 'item_id');
$wasAdded = false;
if (in_array($pid, $item_id_list)) {
foreach ($cart_data as $keys => $values) {
if ($cart_data[$keys]['item_id'] == $pid) {
$cart_data[$keys]['item_qty'] = $cart_data[$keys]['item_qty'] + $qty;
}
}
} else {
$item_array = [
'item_id' => $pid,
'item_qty' => $qty,
];
$cart_data[] = $item_array;
$wasAdded = true;
}
$item_data = json_encode($cart_data);
// cookie() is a Laravel helper to create a cookie object
// note that we don't need to add to time() here, just tell
// the number of seconds when this cookie will expire in the future
$cookie = cookie('shopping_cart_panorama', $item_data, 3600 * 24 * 30, '/');
// response() is a Laravel helper that will create
// a Laravel response object
// intval will convert true -> 1 and false -> 0
return response(intval($wasAdded))->withCookie($cookie);
}
If you try this code out, cookies will be encrypted by default. As you seem to be using this cookie client-side you will need to tell Laravel to not encrypt this cookie.
Go to your project's ./app/Http/Middleware/EncryptCookies.php file and add that cookie name to the $except array:
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
'shopping_cart_panorama',
];
}