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

北战南征 提交于 2020-01-02 03:28:29

问题


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();
  }

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?


回答1:


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();



回答2:


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());


来源:https://stackoverflow.com/questions/35630138/how-to-use-request-all-with-eloquent-models

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