2017-07-15 93 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