Laravel-update-records
提供:Dev Guides
Laravel-レコードの更新
*DB* ファサードと *update* メソッドを使用して、レコードを更新できます。 更新メソッドの構文は、次の表に示すとおりです。
Syntax | int update(string $query, array $bindings = array()) |
Parameters |
|
Returns | int |
Description | Run an update statement against the database. |
例
レコードの更新に関する詳細を理解するには、次の例をご覧ください-
ステップ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 *-* 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 *-そのレコードを編集すると、次の画像に示すようなプロンプトが表示されます。