如何在雄辩的模型中使用Request-> all() [英] How to use Request->all() with Eloquent models
问题描述
我有一个lumen应用程序,我需要在其中存储传入的JSON请求.如果我写这样的代码:
I have a lumen application where I need to store incoming JSON Request. If I write a code like this:
public function store(Request $request)
{
if ($request->isJson())
{
$data = $request->all();
$transaction = new Transaction();
if (array_key_exists('amount', $data))
$transaction->amount = $data['amount'];
if (array_key_exists('typology', $data))
$transaction->typology = $data['typology'];
$result = $transaction->isValid();
if($result === TRUE )
{
$transaction->save();
return $this->response->created();
}
return $this->response->errorBadRequest($result);
}
return $this->response->errorBadRequest();
}
它完美地工作.但是在那种模式下使用Request很无聊,因为我必须检查每个输入字段才能将它们插入到我的模型中.有没有一种快速发送请求到模型的方法?
It works perfectly. But use Request in that mode is boring because I have to check every input field to insert them to my model. Is there a fast way to send request to model?
推荐答案
您可以对雄辩模型进行批量分配,但是您需要首先在模型上设置要允许批量分配的字段.在模型中,设置您的$fillable
数组:
You can do mass assignment to Eloquent models, but you need to first set the fields on your model that you want to allow to be mass assignable. In your model, set your $fillable
array:
class Transaction extends Model {
protected $fillable = ['amount', 'typology'];
}
这将允许amount
和typology
可批量分配.这意味着您可以通过接受数组的方法(例如构造函数或fill()
方法)来分配它们.
This will allow the amount
and typology
to be mass assignable. What this means is that you can assign them through the methods that accept arrays (such as the constructor, or the fill()
method).
使用构造函数的示例:
$data = $request->all();
$transaction = new Transaction($data);
$result = $transaction->isValid();
使用fill()
的示例:
$data = $request->all();
$transaction = new Transaction();
$transaction->fill($data);
$result = $transaction->isValid();
这篇关于如何在雄辩的模型中使用Request-> all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!