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

AydenWH's avatar

Insert session() to database after login

Hello.

I would like to know how to implement a function which deals with the insertion record of the session into the database whenever the user has login into the system.

Current solution

I create a helper SessionCart.php with the create function to add the session() record into the database after user logging in.

SessionCart.php

function create($user_id)
{
    $exists = User::find($user_id)->carts()->where('giftbox_id', $cart['id'])->first();
}

After that, I added the create function at RedirectsUsers.php.

public function redirectPath()
    {
        create(Auth::user()->id);

        if (method_exists($this, 'redirectTo')) {
            return $this->redirectTo();
        }
    }

So, it will create or update the record whenever a user is logging into the system.

===

However, I have the doubt with the solution above whether it is a good practice or not.

Is there a better solution to implement this?

0 likes
2 replies
martinbean's avatar

@Tyris If you’re wanting to create a cart for the user’s current session, then you could have a class that retrieves it or creates it if necessary:

class Cart extends Model
{
    public static function forRequest($request)
    {
        return static::firstOrCreate([
            'session_id' => $request->session()->getId(),
        ]);
    }
}

Then in your controllers, you can retrieve the cart by passing a Request instance:

class CartController extends Controller
{
    public function index(Request $request)
    {
        $cart = Cart::forRequest($request);

        return view('cart.index', compact('cart'));
    }
}
AydenWH's avatar

Hi, @martinbean

Actually, I managed to create a function to insert the session record into Cart models.

It just that the method which I had applied might not be the best practice. I need some bits of advice about that.

If my question is too confusing, please don't hesitate to tell me.

Please or to participate in this conversation.