简体   繁体   中英

laravel - How to insert temporary data to database

I use Laravel 5.4 and I want store my temporary data to table.

For Example:

I created a table named "players" using migrations.

Players: id, name, hero.

Then I created Player Model using php artisan make:model

Then I insert data to players table using eloquent, for example:

$player = new Player;

$player->id = '1;
$player->name = 'NguyenHoang';
$player->hero = 'Ringo';

$player->save();
return view('player');

And all above data will store in players table in my database. But I want it's just a temporary data only. It mean when I close my browser, all data will erase.

Is there anyway to do that ?

Its called the session and is not really specific for laravel. It is a basic php principle. But you would probaby want it out of something like a form and not store it in de database .

// Store a piece of data in the session...
session(['player' => [
'name' => 'NguyenHoang',
'hero' => 'Ringo']]);

// Retrieve a piece of data from the session...
$value = session('player');

Full docs on sessions in laravel https://laravel.com/docs/5.4/session#retrieving-data

The above is probably what you are really looking for, but if you really want to store it temporary in a database, thats also possible:

Driver Prerequisites Database

When using the database session driver, you will need to create a table to contain the session items. Below is an example Schema declaration for the table:

Schema::create('sessions', function ($table) {
    $table->string('id')->unique();
    $table->unsignedInteger('user_id')->nullable();
    $table->string('ip_address', 45)->nullable();
    $table->text('user_agent')->nullable();
    $table->text('payload');
    $table->integer('last_activity'); }); You may use the session:table Artisan command to generate this migration:

php artisan session:table

php artisan migrate

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