例子
观察以下示例以了解有关更新记录的更多信息 -
步骤 1− 执行以下命令创建一个名为StudViewController.
php artisan make:controller StudUpdateController --plain
步骤 2− 成功执行后,您将收到以下输出 −
步骤 3- 将以下代码复制到文件中app/Http/Controllers/ StudUpdateController.php
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 "Record updated successfully.<br/>";
echo '<a href = "/edit-records">Click Here</a> to go back.';
}
}
步骤 4- 创建一个名为的视图文件
resources/views/stud_edit_view.blade.php并将以下代码复制到该文件中。
resources/views/stud_edit_view.blade.php
<html>
<head>
<title>View Student Records</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 }}'>Edit</a></td>
</tr>
@endforeach
</table>
</body>
</html>
步骤 5- 创建另一个名为的视图文件
resources/views/stud_update.php并将以下代码复制到该文件中。
resources/views/stud_update.php
<html>
<head>
<title>Student Management | Edit</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>Name</td>
<td>
<input type = 'text' name = 'stud_name'
value = '<?php echo$users[0]->name; ?>'/>
</td>
</tr>
<tr>
<td colspan = '2'>
<input type = 'submit' value = "Update student" />
</td>
</tr>
</table>
</form>
</body>
</html>
步骤 6 − Add以下几行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− 访问以下 URL 更新数据库中的记录。
http://localhost:8000/edit-records
步骤 8− 输出将如下图所示。
步骤 9− 单击任何记录上的编辑链接,您将被重定向到可以编辑该特定记录的页面。
步骤 10− 输出将如下图所示。
步骤 11− 编辑该记录后,您将看到如下图所示的提示。