Regular expression route constraint for a resource route

偶尔善良 提交于 2019-12-07 03:41:37

问题


Laravel offers the possibility to add regular expression constraint to a route like this:

Route::get('user/{name}', function($name)
{
    //
})
->where('name', '[A-Za-z]+');

it is also possible to create multiple routes for a resource:

Route::resource('photo', 'PhotoController');

I want to add regular expression constraint only to the route GET /photo/{id}

is that possible?


回答1:


As far as I know you can't but you may mimic that using something like this (route filtering):

public function __construct()
{
    $this->beforeFilter('checkParam', array('only' => array('getEdit', 'postUpdate')));
}

This is an example of route filtering using the constructor and here I've filtering only two methods (you may use except or nothing at all) and declared the filter in filters.php file as given below:

Route::filter('checkParam', function($route, $request){
    // one is the default name for the first parameter
    $param1 = $route->parameter('one');
    if(!preg_match('/\d/', $param1)) {
        App::abort(404);
        // Or this one
        throw new Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    }
});

Here, I'm checking the first parameter manually (parameters method returns an array of all parameters passed to the route) and if it's not a digit then throwing NotFoundHttpException exception.

You may also catch the exception by registering a handler like this:

App::missing(function($exception){
    // show a user friendly message or whatever...
});



回答2:


In Laravel 5 resourceful route parameters can be named like this:

Route::resource('user', 'UserController', ['parameters' => [
   'user' => 'id'
]]);

This can be combined with route patterns:

Route::pattern('id', '[0-9]+');

So you can easily define a single global constraint for route parameters and use if for all of your resourceful routes.




回答3:


You should overwrite IlluminateFoundation\Exceptions\Handler :

if ($exception instanceof QueryException) {
            if (str_contains($exception->getMessage(), "Invalid text representation:")) {
                $requestId = $exception->getBindings()[0] ?? "";
                App::abort(404);
               // Or this one
               throw new Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
            } else {
               throw $exception;
            }
        }


来源:https://stackoverflow.com/questions/22622629/regular-expression-route-constraint-for-a-resource-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!