2017-07-15 109 views
0

我使用Laravel 5.4,我希望将临时数据存储到表中。laravel - 如何将临时数据插入数据库

例如:

我创建了一个名为“玩家”使用迁移表。

Players: id, name, hero. 

然后创建播放器型号使用php artisan make:model

然后我用雄辩的数据插入到播放器表,例如:

$player = new Player; 

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

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

及以上的数据将在球员表存储在我的数据库。但我希望它只是一个临时数据。这意味着当我关闭浏览器时,所有的数据都将被清除。

有没有办法做到这一点?

+0

你必须为此编写代码,因为数据在服务器上(而不是浏览器),并且(它本身就是一个数据库)持久化......但你可以使用浏览器的onClose事件来向Laravel发送请求以删除数据 –

回答

1

它被称为会话,并不真正具体为laravel。这是一个基本的PHP原则。但是你可能会想将它从表单中拿出来,而不是将它存储在数据库中。在https://laravel.com/docs/5.4/session#retrieving-data

以上laravel上的会话

// 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'); 

全部文档可能是你真正需要的,但如果你真的要存储在数据库中临时的,也那是可能的:

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