Laravel Controller update method not working

2020-04-19 04:29发布

问题:

I am new in Laravel.

I made controller, Model and views by way/generator by composer php artisan generate:scaffold cities and Its index page (Create and store method) Working well but I don't know what is the problem with update method.

This is my CitiesController method(Update):

public function update($id)
{
    $city = City::findOrFail($id);

    $validator = Validator::make($data = Input::all(), City::$rules);

    if ($validator->fails())
    {
        return Redirect::back()->withErrors($validator)->withInput();
    }

    $city->update($data);
    return Redirect::route('admin.cities.index');
}

This is my model (city):

class City extends \Eloquent {
   protected $primaryKey='city_id';

    public static $rules = [
         'name'     => 'required',
         'image'     => 'mimes:jpeg',
         'parent_id' => 'required',
         'name'      => 'required',
         'english_name'=>'unique:cities,english_name|required'

    ];
    protected $fillable = ['name', 'parent_id', 'english_name','population','phone_prefix','image'];
}

And this is my view (edit):

<ul>
    {{ Form::model($city,array('route'=>array('admin.cities.update',$city->id),'method'=>'PUT','files'=>true)) }}
    <!--Here I included my form-->
    @include('admin.forms._partial.formcity')
    <li>
        {{ Form::submit('submit') }}
    </li>
    {{ Form::close() }}
</ul>

And this is my Route:

Route::group(array('prefix'=>'admin','before'=>'Auth'),function(){
    Route::resource('cities', 'CitiesController');
});

When I click on submit button Laravel throwout this error:

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException

note:My view works well. I think the problem is from controller method, and other methods of this controller like create and store works well too.

回答1:

In your model you have protected $primaryKey='city_id'; but in your view you have:

{{ Form::model($city,array('route'=>array('admin.cities.update',$city->id),'method'=>'PUT','files'=>true)) }}

I mean $city->id should be $city->city_id