Laravel action not defined

2019-01-27 14:10发布

问题:

After updating from Laravel 4.2 to 5.0, I am getting the following message in almost every page of my application:

InvalidArgumentException in UrlGenerator.php line 561: Action ArticlesController@create not defined.

In my routes.php file I have:

Route::get('articles/create', ['as' => 'articles.create', 'uses' => 'ArticlesController@create']);
Route::post('articles/create', ['as' => 'articles.create.handle', 'uses' => 'ArticlesController@handleCreate']);

And in my controller:

class ArticlesController extends Controller {

    public function create()
    {
        $input=null;
        if (Input::old()) {
            $input = Input::old();
        }
        $tagsJson = Tag::all()->toJson();
        $categories = ArticleCategory::all();
        return View::make('admin.articles.create', compact(array('tagsJson', 'categories', 'input')));
    }

    public function handleCreate()
    {
        $input = Input::all();

        if ($input['op']=="preview") {
            return redirect()->action('ArticlesController@create')->withInput();
        } else if ($input['op']=="post") {
            //
        }

    }
}

The error I get comes from this line:

return redirect()->action('ArticlesController@create')->withInput();

Any help? Thanks, Ilias

回答1:

You are getting this error because Laravel 5 uses namespacing by default. The official Laravel 5 upgrade guide says the following about migrating your controllers:

Since we are not going to migrate to full namespacing in this guide, add the app/Http/Controllers directory to the classmap directive of your composer.json file. Next, you can remove the namespace from the abstract app/Http/Controllers/Controller.php base class. Verify that your migrated controllers are extending this base class.

In your app/Providers/RouteServiceProvider.php file, set the namespace property to null.

Listed here under "controllers".

The last line is probably the one that will solve your issue.



回答2:

you have to define routes for any URL generated and if you are pointing a controller method from links or form. actions links to methods depends on Routes ..

When you create a route for this , it will work and the error will disappear .



回答3:

I was getting the same error message, and it was because I'd completely forgotten that I needed to add this to routes/web.php:

Route::get('myUrlPath', 'HomeController@myActionName');

I had been trying to do this from another controller action:

return redirect()->action('HomeController@myActionName')->with('windowTitle', 'Error. Please contact us.')->with('message', $message);