简体   繁体   中英

which to use Cookie or Session? laravel 5.7 - to store data for 5 minutes

guys I'm trying to have 4 steps payment in my application in laravel 5.7

then I wanna store these data in somewhere 4 steps until the payment have been completed and after that I want to store them on database

these 4 steps contains:

  1. select product
  2. select accessories
  3. enter addresses
  4. enter payment detail

now please prefer your ways

which to use? cookie or session or something else ?

I would use session but I want those data destroyed after 5 minutes and if I choose session lifetime to 5 minutes all of session data will destroy like my login session and I just want destroy the session that I created.

The data you want to store temporarily is a cart quote data in terms of e-commerce. You can store this data in the database, with a timestamp column expires_at having value of current time + 5 minutes .

Then in your model global scope, which will always filter queries and only get non-expired data :

/**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('expires_at', function (Builder $builder) {
            $builder->where('expires_at', '<=', Carbon::now());
        });
    }
  • The advantage of having this is, the data you can used for abandoned cart reports.
  • In this data, mostly addresses, products will not contain all details but references using foreign keys to respective tables. If its not the case, I would recommend you to normalise your database.
  • Also, if you desire you can delete this data in a weekly cron to delete let's say all expired entries of last week.

Sessions provide a way to store information about the user across multiple requests, you should check https://laravel.com/docs/5.7/session for me is the best option.In the session driver configuration option you can defines where session data will be stored for each request, for example cookie , were sessions are stored in secure, encrypted cookies. Then for your problem about destroy de data you can use the forget method will remove a piece of data from the session. If you would like to remove all data from the session, you may use the flush method.

// Forget a single key...
  $request->session()->forget('key');
//or
  $request->session()->flush();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM