使用DB::update()方法更新記錄。 DB::update()方法的語法如下表中所示。
語法 | int update(string $query, array $bindings = array()) |
---|---|
參數 |
|
返回值 | int |
描述 |
在資料庫上運行一個更新語句
|
示例
第1步- 執行以下命令來創建一個名為 StudUpdateController 的控制器。
php artisan make:controller StudUpdateController
第2步 - 成功執行後,您會收到以下輸出 -


第3步 - 將以下代碼複製到檔 - app/Http/Controllers/StudUpdateController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; use App\Http\Requests; use App\Http\Controllers\Controller; class StudUpdateController extends Controller { public function index(){ $users = DB::select('select * from student'); return view('stud_edit_view',['users'=>$users]); } public function show($id) { $users = DB::select('select * from student where id = ?',[$id]); return view('stud_update',['users'=>$users]); } public function edit(Request $request,$id) { $name = $request->input('stud_name'); DB::update('update student set name = ? where id = ?',[$name,$id]); echo "更新記錄成功.<br/>"; echo '<a href = "/edit-records">點擊這裏</a> 返回'; } }
第4步 - 創建一個名為 resources/views/stud_edit_view.blade.php 的視圖檔,並複製下麵的代碼到此檔中。
resources/views/stud_edit_view.blade.php
<html> <head> <title>查看學生記錄</title> </head> <body> <table border = "1"> <tr> <td>ID</td> <td>Name</td> <td>Edit</td> </tr> @foreach ($users as $user) <tr> <td>{{ $user->id }}</td> <td>{{ $user->name }}</td> <td><a href = 'edit/{{ $user->id }}'>編輯</a></td> </tr> @endforeach </table> </body> </html>
第5步 - 創建一個名為 resources/views/stud_update.php 的另一個視圖檔,並複製下麵的代碼放入下麵的檔中。
resources/views/stud_update.php
<html> <head> <title>編輯 | 學生管理</title> </head> <body> <form action = "/edit/<?php echo $users[0]->id; ?>" method = "post"> <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>"> <table> <tr> <td>名字</td> <td> <input type = 'text' name = 'stud_name' value = '<?php echo$users[0]->name; ?>'/> </td> </tr> <tr> <td colspan = '2'> <input type = 'submit' value = "更新學生資訊" /> </td> </tr> </table> </form> </body> </html>
第6步 - 添加以下行到檔 - app/Http/routes.php.
app/Http/routes.php
Route::get('edit-records','StudUpdateController@index'); Route::get('edit/{id}','StudUpdateController@show'); Route::post('edit/{id}','StudUpdateController@edit');
第7步 - 請訪問以下網址資料庫中更新記錄。
http://localhost:8000/edit-records
第8步 - 輸出結果如下圖所示


步驟9- 點擊記錄"編輯"鏈接,將被重定向到一個頁面,可以編輯特定的記錄。
第10步 - 輸出如下面圖所示。


第11步 - 編輯這條記錄後,會看到一個提示圖如下圖所示。


上一篇:
Laravel檢索查詢數據
下一篇:
Laravel刪除數據