LARAVEL: How to make multiple inserts from inputs

Gabriel Guerra
2 min readFeb 27, 2019

Sometimes we need more than just a simple insertion. For example: imagine you are saving answers from a briefing. Maybe you just don’t even know what questions are or maybe you just hate typing unecessarily.

In way or another you can save the inputs very easily in Laravel.

Photo licensing: https://shutr.bz/2GNTREV

We’ll make use of the method except() from the Request Class (https://laravel.com/api/5.3/Illuminate/Http/Request.html).

But first, you must check two little things:

  1. If the method you’re using to process the inserts is receiving Request by parameter. If not so, add “Request $request” to your method.
  2. If your model have the attribute “fillable” properly set. There, should be defined the fields you want to allow what Laravel calls “Mass assignment”.

Excerpt from the Laravel manual:

Mass Assignment

You may also use the create method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.

Now let’s talk about the except() method. It’s a simple way to get all your submitted form inputs, except the ones you pass through parameter to the method. Like the example below:

$inputs = $request->except('_method', '_token');

That code sample up above is excluding _method and _token values from the inputs array.

You can use this technique to exclude all the fields you don’t need.

Now that we have just the inputs we want, let’s loop through the array and set an insert for each iteration:

foreach ($inputs as $key => $value) {    //Instantiate your object
$answers = new QuestionAnswers;

//Set the fields and values for the insertion
$answers->briefings_id = 4;
$answers->questions_id = $key;
$answers->answer = $value;

//Do the insertion
$answers->save();
};

That’s it! You’ve done it :)

--

--