我是Laravel的新手,据我所知,将数据形式存储到数据库的方式有三种,如果我错了,请纠正我:
第一种方法:从模型实例化对象
$tutor = new Tutor();
$tutor ->name = $request->name;
// in some tutorials they use:
// $tutor->name = request('name');
// what is the difference?
$tutor ->salary = $request->salary;
$tutor->save();
第二种方式:将对象转为数组
$tutor = array([
'name' => $request->name, // vs 'name' => $request->input('name'), what is the difference?
'salary' => $request->salary
]);
$tutor->save(); // Do I need to save here?
第三种方法:使用全局辅助方法
$tutor = Tutor::create($request->all());
最佳答案
difference between
request('name')
and$request('name');
request()
是一个全局辅助函数,可以在任何地方使用来访问 HTTP 请求对象
$request
是传递给 Controller 函数的参数,这意味着传递给该 Controller 的THE请求在通过表单请求类验证数据时非常有用
Do I need to save data here?
第二种方式根本不应该像所写的那样工作,你可能是说
$tutor = new Tutor([
'name' => $request->name,
'salary' => $request->salary
]);
$tutor->save();
这是手动删除额外的表单发布数据,这与
没有什么不同$tutor = new Tutor();
$tutor->create(request()->only(['name', 'salary']));
$request->name
vs 'name' => $request->input('name') what is the difference?
使用input
方法意味着从用户输入中获取名称参数,无论使用什么HTTP方法GET
或POST
或引用the docs
检索输入值
使用一些简单的方法,您可以从 Illuminate\Http\Request
实例访问所有用户输入,而不必担心请求使用了哪个 HTTP 谓词。无论 HTTP 动词如何,input
方法都可用于检索用户输入:
$name = $request->input('name');
第三种方式使用请求中发布的所有内容进行批量分配,包括您不希望从恶意用户(黑客)那里获取的内容
不惜一切代价避免它
希望这有帮助
关于mysql - 有多少种方法可以将 Laravel 表单中的数据存储到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58695685/