Puggan Se
Puggan Se

Reputation: 5846

How to route path to 404 in Laravel

Currenlty have a ImageController that catch a route under /media/upload/ and a IndexController that have a missingMethod() that catch other urls.

But I don't want the IndexController to catch /media/-urls

What i had:

<?php
Route::get('media/upload/{userId}/{productId}/view/{size}/{filename}',
    'ImageController@anyView');
Route::controllers(['/' => 'IndexController']);

tried to add a 404-route using:

<?php
Route::get('media/{path?}/{path2?}/{path3?}/{path4?}/{path5?}/{path6?}',
    function() {throw new NotFoundHttpException();});

But I if the url has more then 8 '/' then the IndexController catch the URL.

How can I write a route that catch all media/-urls (except the one that ImageController use)?

Upvotes: 0

Views: 210

Answers (2)

apokryfos
apokryfos

Reputation: 40653

Basically if you want media* to be caught then do:

Route::get('media/upload/{userId}/{productId}/view/{size}/{filename}',
'ImageController@anyView');
 Route::get("media/{param?}", function ($param) {
       throw new NotFoundHttpException();
 })->where("param",".*")
 Route::controllers(['/' => 'IndexController']);

That should catch everything after media and put it into $param in your route handler. Ideally anything that matches the first route will not be caught by the second and then anything that matches /media* will not be caught by index.

However the order is important.

Upvotes: 1

Kushagra Saxena
Kushagra Saxena

Reputation: 659

First of all you will have to write the route that you want to catch in the ImageController above the other one in api.php file. Now the best approach to do this can to group your both of the routes in a CustomMiddleware that you can create using the command

php artisan make:middleware MyMiddleware

Now use this middleware to check the number of / and the pass the request or throw an exception as per your requirement.

Upvotes: 0

Related Questions