简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM