例子
步骤 1− 执行以下命令创建一个名为StudInsertController
php artisan make:controller StudInsertController --plain
步骤 2− 成功执行步骤 1 后,您将收到以下输出 −
步骤 3- 将以下代码复制到文件中
app/Http/Controllers/StudInsertController.php
app/Http/Controllers/StudInsertController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class StudInsertController extends Controller {
public function insertform() {
return view('stud_create');
}
public function insert(Request $request) {
$name = $request->input('stud_name');
DB::insert('insert into student (name) values(?)',[$name]);
echo "Record inserted successfully.<br/>";
echo '<a href = "/insert">Click Here</a> to go back.';
}
}
步骤 4- 创建一个名为的视图文件resources/views/stud_create.php并将以下代码复制到该文件中。
resources/views/stud_create.php
<html>
<head>
<title>Student Management | Add</title>
</head>
<body>
<form action = "/create" method = "post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<table>
<tr>
<td>Name</td>
<td><input type='text' name='stud_name' /></td>
</tr>
<tr>
<td colspan = '2'>
<input type = 'submit' value = "Add student"/>
</td>
</tr>
</table>
</form>
</body>
</html>
步骤 5- 添加以下行app/Http/routes.php.
app/Http/routes.php
Route::get('insert','StudInsertController@insertform');
Route::post('create','StudInsertController@insert');
步骤 6− 访问以下 URL 以在数据库中插入记录。
http://localhost:8000/insert
步骤 7− 输出将如下图所示。