11

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?

3 Answers3

24

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();
patricus
  • 59,488
  • 15
  • 143
  • 145
10

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());
chanafdo
  • 5,016
  • 3
  • 29
  • 46
  • @patricus answer is more complete as it contains `isValid()` call which the code of the questioner contains. And it stops me from using `$fooModel->some_foo_col = $request->get('some_foo_col ');` ugly code. – Roland Jul 09 '18 at 08:28
0
  1. Create your TransactionRequest with rules extends FormRequest
  public function store(TransactionRequest $request)
  {

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

      $transaction->save();
  }
Lost user
  • 11
  • 3