1

I wanted to update multiple rows in the database and have found a way to do it. but it does not seem like the best way to do it, since it is doing it in multiple calls at the moment.

I wanted to now if there is a better way to do this.

The homecontroller with the updatePersons function:

<?php    
class HomeController extends BaseController {

    public function index()
    {
        $persons = Person::get();
        return View::make('hello')
        ->with(compact('persons'));
    }

    public function updatePersons()
    {
        $persons = Person::get();

        foreach ($persons as $person) {
            $person->fname = Input::get('fname'.$person->id);
            $person->lname = Input::get('lname'.$person->id);

            $person->save();
        }

        return Redirect::route('home')->with('succes', 'Siden er opdateret');
    }

}

the view with the form

@extends('layouts.master')
@section('content')

<div class="container">
    <ul class="list-group">
        {{ Form::open(array('route'=>'personUpdate', 'method' => 'post')) }}
            @foreach ($persons as $person)
                <li class="list-group-item">
                {{ Form::text('fname'.$person->id,$person->fname,array('class'=>'form-control', 'placeholder'=>'fname')) }}
                {{ Form::text('lname'.$person->id,$person->lname,array('class'=>'form-control', 'placeholder'=>'lname')) }}
                </li>  
            @endforeach

                <li class="list-group-item">
                <div class="box-footer">
                            <button type="submit" class="btn btn-primary">Update</button>
                        </div>
                </li>
        {{ Form::close() }}
    </ul>
</div>
</div>
@stop

The routes:

<?php

Route::get('/', array('as'=>'home', 'uses'=>'HomeController@index'));

Route::post('/', array('as'=>'personUpdate', 'uses'=>'HomeController@updatePersons'));

I have tried to use the savemany() function on $persons after the foreach loop in updatePersons() but with no results.

1 Answer 1

1

If you're updating many rows with each with different values, there's no easier way to do it.

Could you think of how you'd write this in SQL?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.