Laravel模型中如何获取表单提交的$request全部数据?
Laravel 表单请求数据批量存入模型的实现
1. 配置模型的批量赋值权限
Laravel 默认禁止批量赋值,必须在模型中声明允许的字段(白名单)或者排除字段(黑名单):
// 示例模型:app/Models/Post.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { // 白名单:指定允许批量赋值的字段(对应表单input的name属性) protected $fillable = ['title', 'content', 'author']; // 或者使用黑名单:空数组表示所有字段都允许批量赋值 // protected $guarded = []; }
2. 控制器中处理请求并保存数据
有两种常用的实现方式:
方式一:使用 create() 方法直接创建
// 示例控制器:app/Http/Controllers/PostController.php namespace App\Http\Controllers; use App\Models\Post; use Illuminate\Http\Request; class PostController extends Controller { public function store(Request $request) { // 直接传入全部请求数据(需模型配置好批量赋值权限) Post::create($request->all()); // 更安全的做法:只取需要的字段,避免存入无关参数(如_token) // Post::create($request->only(['title', 'content', 'author'])); return redirect()->back()->with('success', '数据保存成功'); } }
方式二:实例化模型后填充并保存
适合需要额外补充字段(如当前用户ID)的场景:
public function store(Request $request) { $post = new Post(); // 填充请求数据 $post->fill($request->all()); // 补充表单未提交的字段 $post->user_id = auth()->id(); // 保存到数据库 $post->save(); return redirect()->back()->with('success', '数据保存成功'); }
3. 关键注意事项
- 必须配置模型的
$fillable或$guarded,否则会抛出MassAssignmentException异常 - 建议先做表单验证,确保数据合法性,示例:
$validatedData = $request->validate([ 'title' => 'required|string|max:255', 'content' => 'required|text', ]); Post::create($validatedData);
- 避免直接存入
$request->all(),尽量用only()或except()过滤数据,防止敏感字段被恶意提交
内容的提问来源于stack exchange,提问作者mahbub
相关产品推荐
相关产品推荐

