Home > OS >  Laravel 5.8: How to insert array session value
Laravel 5.8: How to insert array session value

Time:09-22

I'm working with Laravel 5.8 and in this project, I want to insert a session value into the DB:

if(session('video-products')){
    UserVideo::create([
         'user_id' => auth()->user()->usr_id,
         'product_id' => session('video-products'),
         'order_id' => $orderId,
    ]);
}

But it does not work out and inserts nothing. And when I dd(session('video-products')), I get this:

array:1 [▼
  0 => 33
]

And the table field goes like this: product_id varchar(2500) utf8_general_ci

So what's going wrong here? How can I properly insert this array session value?

CodePudding user response:

because your try to insert an array in the product_id column. Try:

if(session('video-products')){
    UserVideo::create([
         'user_id' => auth()->user()->usr_id,
         'product_id' => session('video-products')[0],
         'order_id' => $orderId,
    ]);
}

If more Values:

if(session('video-products')){
foreach(session('video-products') as $sid){
  UserVideo::create([
             'user_id' => auth()->user()->usr_id,
             'product_id' => $sid,
             'order_id' => $orderId,
        ]);

}
      
}

CodePudding user response:

You need to loop on it to create all the entries

if(is_array(session('video-products')) && session('video-products')){
    $userVideoToBeInserted = [];
    foreach(session('video-products') as $productId) {
        $userVideoToBeInserted[] = [
            'user_id' => auth()->user()->usr_id,
            'product_id' => $productId,
            'order_id' => $orderId,
        ];
    }
    UserVideo::insert($userVideoToBeInserted);
}

if you have a unicity issue with the product ids in session, to avoid dupplicate, you can use $productId as index

if(is_array(session('video-products')) && session('video-products')){
    $userVideoToBeInserted = [];
    foreach(session('video-products') as $productId) {
        $userVideoToBeInserted[$productId] = [
            'user_id' => auth()->user()->usr_id,
            'product_id' => $productId,
            'order_id' => $orderId,
        ];
    }
    UserVideo::insert($userVideoToBeInserted);
}
  • Related