Laravel - Overriding a resource route into a diffe

2019-06-24 07:35发布

Laravel's routing doesn't seem to be working as expected? From what I understand, if I intend to override a route, all I need to do is to put the expected route before the other one.

What I have is something like this:

Route::group(array('before'=>'defaultLoads'), function(){
    Route::post('newsletter', 'NewsletterController@store');

    Route::group(array('before'=>'login'), function(){
        Route::resource('newsletter','NewsletterController');
    }
});

Which I assumed that if i post to this route http://domain.com/newsletter it should only run the defaultLoads route filter.

However, when I run php artisan routes, I get this:

| | POST newsletter | newsletter.store | NewsletterController@store | defaultLoads, login | |

Although it reads the route correctly (php artisan loads that correct route in the correct place) but the resource route's filter affected the route even when it's not in that filter group.

So my question:

  1. Is this how Laravel works?

  2. If so, is it possible for me to override that POST->newsletter route without actually doing the following?

    Route::group(array('before'=>'defaultLoads'), function(){
    Route::post('newsletter', 'NewsletterController@store');
    
    Route::group(array('before'=>'login'), function(){
        Route::get('newsletter','NewsletterController@get');
        Route::get('newsletter/{id}', 'NewsletterController@show');
        //etc all the rest of the routes except post
    }});
    

1条回答
孤傲高冷的网名
2楼-- · 2019-06-24 07:51

Actually overriding in that way works in cases where you need to override the actual route that is being matched. For example when you need to override a route with a parameter, with something hardcoded:

Route::get('newsletter/custom', ...);
Route::get('newsletter/{param}', ...); // this is overriden by the first route

In your case however, your route definitions are identical (both must match newsletter for a post request). That means that the last one will override the first one (and any filters applied to it in the current context). So you should be overrding it after the resource route definition:

Route::group(array('before'=>'defaultLoads'), function()
{
    Route::group(array('before'=>'login'), function()
    {
        Route::resource('newsletter','NewsletterController');
    }

    Route::post('newsletter', 'NewsletterController@store');
});

Your artisan routes for it should look like this now:

POST newsletter | NewsletterController@store | | defaultLoads
查看更多
登录 后发表回答