MethodNotAllowedHttpException laravel-4

2020-04-03 04:14发布

问题:

Form :

{{ Form::open(array('url' => 'user/create', 'files' => true)) }}

Route :

Route::resource('user', 'UserController');

UserController.php

  class UserController extends BaseController {

    public function index()
    {
        return 'hi11';
        //return View::make('home.index');
    }
    public function create()
    {
        return 'hi22';
        //return View::make('home.index');
    }

}

This code gives
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException

回答1:

I'd just like to add my own discovery along these lines... Maybe this will save someone else the head-scratching I just performed.

I too implemented the Route::resource mechanism. I couldn't figure out why my create was working but my update was not. It turns out you can't reuse the same form code exactly, the form that does an update must use the method PUT or PATCH. Why update couldn't be a POST is beyond me.

That is to say, the opening form tag for an update must look like this:

Form::model($thing, array(
    'method' => 'PUT', 
    'route' => array('things.update', $thing->id)
    )

Without specifying method => PUT, you get this not-helpful error.



回答2:

Because in your roures you use resourse controller, you can use only specific paths and actions, described in documentation http://laravel.com/docs/controllers#resource-controllers.

user/create ( UserController::create ) is where you need to show the form for adding a new user.

The actual storage of the user should be done in user/store i.e. your form must be send data to UserController::store() method.

In your case if you POST your form only to 'url' => 'user', this should automatically send data to the correct method.



回答3:

Laravel 4 resources have named routes - just use those:

{{ Form::open(array('route' => 'user.create', 'files' => true)) }}


回答4:

this is how I'm doing it, it might help someone, can be improved, but this would be main idea.

@if(isset($data))
    {{ Form::open(['route'=>['blog.update', isset($data) ? $data->slug : null],'method' => 'patch','role' => 'form', 'class' => 'blog-form form-horizontal']) }}
@else
    {{ Form::open(['route'=>'blog.store','role' => 'form', 'class' => 'blog-form form-horizontal']) }}
@endif