laravel中fill()方法的使用
1.个人理解fill方法就是用来过滤前端传输过来的与模型中对应的多余字段
下面我们来看看简单的使用
1.1数据表
1 CREATE TABLE `user` ( 2 `id` int(5) NOT NULL AUTO_INCREMENT, 3 `username` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, 4 `password` varchar(999) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, 5 PRIMARY KEY (`id`) 6 ) ENGINE=InnoDB AUTO_INCREMENT=68 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
1.2模板路由
Route::get('/', function () { return view('index'); });
1.3控制器
Route::post('demo','DemoController@demo');
2.视图层代码(这里注意第三个字段测试使用)
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" 6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>个人测试网页</title> 9 10 </head> 11 <body> 12 <form action="demo" method="post"> 13 {{csrf_field()}} 14 USERNAME:<input type="text" name="username" ><br> 15 PASSWORD:<input type="password" name="password"><br> 16 测试:<input type="text" name="test"><br> 17 <input type="submit" value="提交"> 18 19 </form> 20 </body> 21 </html>
3.控制器层代码
1 <?php 2 3 namespace App\Http\Controllers; 4 5 use App\Models\User; 6 use Illuminate\Http\Request; 7 8 class DemoController extends Controller 9 { 10 // 11 public function demo(Request $request) 12 { 13 $data=new User(); 14 $data->fill($request->except('_token')); 15 $data->username=$request->username; 16 $data->password=$request->password; 17 return $data->save(); 18 19 //User::create(['username'=>'sda','password'=>'sad']); 20 } 21 }