Laravel 编码实践/最优化存储方法
Laravel Coding Practice / Most Optimised Method to Store
Laravel 文档说应该按如下方式存储:
public function store(Request $request)
{
// Validate the request...
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
}
但是,为什么不直接如下:
public function store(Request $request)
{
Flight::create($request->all());
}
上面的例子很简单,因为它只有一个字段。但是我认为用很多字段做某事并且必须分配每个字段而不是像第二个示例那样只传递整个 $request 是相当乏味的?
第一个选项可以让您更好地控制新模型中的内容。如果您存储请求中的所有内容,那么用户可能会在 store
方法中注入您不想为新模型存储的字段。
例如,您的航班有列 is_top_priority
,在您的 Flight
模型中声明为可填写,但在创建新航班时,您只想为航班设置 name
(并将 is_top_priority
保留为空,或者它在 table 中的默认值为 0)。如果你写 Flight::create($request->all());
那么用户可以注入 <input name="is_top_priority" value="1">
并利用你的代码。
这就是不推荐使用fill($request->all())
的原因。使用 $request->only(...)
或按照第一个示例中提供的方式手动分配每个需要的字段。
例如,您的模型有一些字段,如姓名、电子邮件、密码、状态等。
请求验证姓名、电子邮件和密码,如果您这样做:
Flight::create($request->all());
客户端可以发送其他字段状态,但您手动更改状态。我这样做:
Flight::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => $request->get('password'),
'status' =>config('params.flight.status.not_active'),
]);
Laravel 文档说应该按如下方式存储:
public function store(Request $request)
{
// Validate the request...
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
}
但是,为什么不直接如下:
public function store(Request $request)
{
Flight::create($request->all());
}
上面的例子很简单,因为它只有一个字段。但是我认为用很多字段做某事并且必须分配每个字段而不是像第二个示例那样只传递整个 $request 是相当乏味的?
第一个选项可以让您更好地控制新模型中的内容。如果您存储请求中的所有内容,那么用户可能会在 store
方法中注入您不想为新模型存储的字段。
例如,您的航班有列 is_top_priority
,在您的 Flight
模型中声明为可填写,但在创建新航班时,您只想为航班设置 name
(并将 is_top_priority
保留为空,或者它在 table 中的默认值为 0)。如果你写 Flight::create($request->all());
那么用户可以注入 <input name="is_top_priority" value="1">
并利用你的代码。
这就是不推荐使用fill($request->all())
的原因。使用 $request->only(...)
或按照第一个示例中提供的方式手动分配每个需要的字段。
例如,您的模型有一些字段,如姓名、电子邮件、密码、状态等。 请求验证姓名、电子邮件和密码,如果您这样做:
Flight::create($request->all());
客户端可以发送其他字段状态,但您手动更改状态。我这样做:
Flight::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => $request->get('password'),
'status' =>config('params.flight.status.not_active'),
]);