How to use Request->all() with Eloquent models

不打扰是莪最后的温柔 提交于 2019-12-05 05:14:02

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'];
}

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).

An example using the constructor:

$data = $request->all();
$transaction = new Transaction($data);

$result = $transaction->isValid();

An example using fill():

$data = $request->all();
$transaction = new Transaction();
$transaction->fill($data);

$result = $transaction->isValid();

You can either use fill method or the constructor. First you must include all mass assignable properties in fillable property of your model

Method 1 (Use constructor)

$transaction = new Transaction($request->all());

Method 2 (Use fill method)

$transaction = new Transaction();
$transaction->fill($request->all());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!