猿问

如何从会话 Laravel 中删除项目

如何从 Laravel 的会话中删除数据。我不想通过单击单个删除按钮来删除所有数据。我对每个数据都有删除按钮,所以想一一删除。我目前的代码如下:


public function deleteProduct(Request $request){

    $id = $request->productId;// this id i want to delete which i get from view

    $products = $request->session()->get('product');


    foreach ($products as $key => $value)

    {

        if ($value['id'] == $id)

        {

            unset($products [$key]);

        }

    }


    //then you can redirect or whatever you need

    return redirect()->back();

}

我也试过这个


foreach ($products as $product)

{

    if ($product->id == $id)

    {

        $products->forget($product);

    }

}

我在会话中的数据格式如下


[

{

id: 2,

name: "Marlene Reichert",

description: "Debitis asperiores sed sit assumenda unde quo natus. Consequatur est labore tenetur quae. Eius distinctio ea omnis aspernatur porro earum quae.",

category_id: 3,

price: 76,

image: "http://loremflickr.com/400/300?random=71",

created_at: "2019-07-16 10:12:27",

updated_at: "2019-07-16 10:12:27",

qty: 1

},

{

id: 6,

name: "Kaylin Emard",

description: "Et aperiam omnis nam iure id non fugiat. Excepturi voluptatem ipsam magnam. Esse asperiores ducimus enim et.",

category_id: 8,

price: 14,

image: "http://loremflickr.com/400/300?random=17",

created_at: "2019-07-16 10:12:27",

updated_at: "2019-07-16 10:12:27",

qty: 1

},

{

id: 5,

name: "Prof. Iliana Mohr",

description: "Autem sequi esse laudantium ut ut explicabo enim. Corporis cupiditate dolorum et ratione sequi architecto. Vitae enim ex hic nihil.",

category_id: 2,

price: 207,

image: "http://loremflickr.com/400/300?random=99",

created_at: "2019-07-16 10:12:27",

updated_at: "2019-07-16 10:12:27",

qty: 1

}

]


临摹微笑
浏览 174回答 3
3回答

互换的青春

试试这个代码$request->session()->forget('product');

蝴蝶不菲

这$request->session()->forget('product');是从会话中删除整个密钥,而您不希望那样。所以...如何从 Laravel 的会话中删除数据。在你的情况下,你这样做:public function deleteProduct(Request $request){    $id = $request->productId;    // Get the array from session.    $products = $request->session()->get('product');    // Remove unwanted key from array.    foreach ($products as $key => $value)    {        if ($value->id == $id)        {            unset($products[$key]);        }    }    // Override the session.    $request->session()->put('product', $products);    return redirect()->back();}deleteAllProducts()例如,如果有一天您在系统中添加了该功能,那么您就可以很好地调用$request->session()->forget('product');

繁星coding

您不能将 foreach 用于数组,而是使用 for 循环for($x = 0;$x<sizeOf($products);$x++){&nbsp; $product = $products[$x];&nbsp; #then do your manipulation here}
随时随地看视频慕课网APP
我要回答