Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ThyagoSB's avatar

Make a select with session information

I have my codes in the session, and I wanted to make a select in the query by taking the session codes as a condition, and then sending the information to the view

0 likes
7 replies
ThyagoSB's avatar

session()->push('session_cart', $id); $result= DB::select('select * from products where id in (?)',[session()]); return view('list', compact('result'));

Snapey's avatar

Formatted

session()->push('session_cart', $id); 

$result= DB::select('select * from products where id in (?)',[session()]);

return view('list', compact('result'));

So I'm guessing session_cart is an array of product ids?

Have you checked that?

Is there a good reason you don't use Eloquent or Query Builder?

ThyagoSB's avatar

Exactly, the session_cart are product IDs, but I do not know how to do the select with these IDs, I'm learning Laravel and I do not know how to use these Eloquent or Query Builder, how would I do this select?

Snapey's avatar

Eloquent way;

$cart = Product::whereIn('id', session('session_cart'))->get();

return view('list', compact('cart'));

DB way;

$cart = DB::table('products')->whereIn('id', session('session_cart'))->get();

return view('list', compact('cart'));

In the view you will have a $cart variable which is a collection of matching products

(because I don't believe in using ambiguous terms like $results unless its a football match)

ThyagoSB's avatar

That's exactly what I was trying to do, thank you very much for the help

Snapey's avatar
Snapey
Best Answer
Level 122

please mark it answered

Please or to participate in this conversation.