Reputation: 884
Laravel documentation says one should store as follows:
public function store(Request $request)
{
// Validate the request...
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
}
However, why not just as follows:
public function store(Request $request)
{
Flight::create($request->all());
}
The above example is quite easy, since it only has one field. But I imagine its rather tedious to do something with many fields and have to assign each one as opposed to just passing the whole $request as in the second example?
Upvotes: 2
Views: 45
Reputation: 1732
For example your model have some fields like name, email, password,status and etc. Request validate name, email and password and if you do this:
Flight::create($request->all());
Client can send with other fields status, but you change status manually. I do this:
Flight::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => $request->get('password'),
'status' =>config('params.flight.status.not_active'),
]);
Upvotes: 1
Reputation: 1410
First option gives you better control as to what goes into new model. If you store everything from the request then user might inject fields that you don't want to be stored for a new model in your store
method.
For example, your flight has column is_top_priority
that is declared as fillable in your Flight
model, but when creating new flight you want to set only name
for you flight (and leave is_top_priority
as null or maybe it has default value of 0 in your table). If you write Flight::create($request->all());
then user can inject <input name="is_top_priority" value="1">
and get advantage of your code.
That is why it is not recommended to use fill($request->all())
. Use $request->only(...)
or assign each needed field manually as provided in your first example.
Upvotes: 2