Michael Kirkegaard
Michael Kirkegaard

Reputation: 379

Update multible rows in laravel 4

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.

Upvotes: 1

Views: 52

Answers (1)

Lance Pioch
Lance Pioch

Reputation: 1167

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?

Upvotes: 1

Related Questions