0

I have a resource and I'm trying to set up the update controller. In my case my edit form has many inputs and I need to update the database with them but there might be columns in the database not changed by the edit form. So I have my controller like this:

public function update($id)
{

    $hostess = Hostess::find($id);

    $inputs=Input::all();

    foreach ($inputs as $key => $value) {
        $hostess->$key= $value;
    }

    if ($hostess->save())
    {
        return Redirect::route('hostesses.show', $hostess->id);
    }

    return Redirect::back()->withInput()->withErrors($hostess->getErrors());
}

This gives me an error because I am using PUT in my view and I get

 Column not found: 1054 Unknown column '_method' in 'field list'

Because my Input::all() is getting the hidden inputs for the PUT method. I can use Input::except() for that, but is that the proper way of updating with laravel?

2 Answers 2

4

You can actually do something like this:

$hostess   = Hostess::find($id)

$post_data = Input::all();
// or
$post_data = Input::except('_method');

// warning untested if block below
if ($hostess->update($post_data))
{
    return Redirect::route('hostesses.show', $hostess->id);
}

return Redirect::back()->withInput()->withErrors($hostess->getErrors());

As short as that would update all available key and value pairs.

Do note that you have to add the columns to the $fillable property in the model to avoid the mass assignment warning.

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

2 Comments

Your answer is the way to go, but to make it even better add as an alternative fill(Input::all()) or new Hostess(Input::all()) as simpler, but when $fillable is set on the model.
Thanks, this looks like the proper way to go.
0

You could do something like this:

$inputs = Input::all();
$inputs = array_except($input, '_method');

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.