Home Ask Login Register

Developers Planet

Your answer is one click away!

Ben February 2016

A more efficient way of saving 125 columns in a Laravel controller

I have a rather large table that has 125 data inputs, each of which has to be saved in a separate column.

I have named each HTML input as 1,2,3 etc... and the same within the table, to hopefully help things.

At the moment, I have the following code:

$observation = new Observation();
$observation->site_id = Input::get('site_id');
$observation->result = Input::get('1');
$observation->result_id = '1';

Is there a way I could use a loop to iterate through the 125 data inputs (Input::get('X') and result_id = 'X') and then save them all?


Jilson Thomas February 2016

for($i=1; $i<=125; $i++) {

    $data[$i] = [
        'result'=>Input::get($i), 'result_id'=>$i

Using Query builder:

DB::table('table')->insert($data); // Change this with your table name. 

and if you want to use Eloquent:


mmccaff February 2016

You can use something like this pattern in your controller to handle creating new Observations and editing existing Observations without worrying about the specific attribute names:

// get all non-empty inputs except 'token' 
$inputs = array_filter(Input::except('_token'), 'strlen');

// assuming 'id' is your primary key and sent as an input in your form
if (Input::has('id'))
    // An edit

    $id = Input::get('id');
    $observation = Observation::find($id);

    foreach ($inputs as $key => $value) 
            $observation->$key = $value;
    // A create

    $observation = new Observation($inputs);

This solution doesn't force you to use sequential column names or html input names like 1..125 and will allow you to use more meaningful column names if you prefer. However, it does assume that your column names (and therefore object attributes) are the same as the html input names.

Related, but you might also like to know that if you use the HTML helpers in the Blade view template to construct your form, and open the form with Form::model, it will fill even fill in the values of the inputs using the object that you pass to it.

For example, in the view:

{{ Form::model($observation) }}

Post Status

Asked in February 2016
Viewed 3,217 times
Voted 7
Answered 2 times


Leave an answer

Quote of the day: live life