Regular expression route restriction for resource route

Laravel offers the ability to add a regular expression constraint to the following route:

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

It is also possible to create several routes for the resource:

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

I want to add regex restriction only to the route GET /photo/{id}

perhaps?

+6
source share
3 answers

As far as I know, you cannot, but you can imitate this 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 filter only two methods (you can use exceptor nothing at all) and declared a filter in the filters.phpfile as follows:

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;
    }
});

( parameters , ), , NotFoundHttpException.

, :

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

Laravel 5 :

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

:

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

, if .

+8

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;
            }
        }
0

Source: https://habr.com/ru/post/1533249/


All Articles