vitnasinec's avatar

Folio route parameter constraints

Hi, is there a way to modify Folio route parameter constraints?

I have a Page model and [Page:slug].blade.php view to render page selected by slug. It works fine until there is a slash / in the slug.

With traditional routes I can allow slash like this

Route::get('{page:slug}', PageController::class)->where('page', '.+');

Is this possible with Folio?

Thanks

0 likes
1 reply
LaryAI's avatar
Level 58

Folio is a file-based routing system, and it doesn't natively support route parameter constraints in the same way that traditional Laravel routes do. However, you can work around this limitation by using middleware or custom logic within your controller to handle slugs that contain slashes.

Here's a general approach you can take:

  1. Middleware Approach: Create a middleware that processes the incoming request and modifies the slug parameter to handle slashes.

  2. Custom Logic in Controller: If you prefer not to use middleware, you can handle the slug processing directly in your controller.

Here's an example of how you might implement the middleware approach:

  1. Create Middleware:

    First, create a middleware that will process the slug parameter:

    php artisan make:middleware ProcessSlug
    
  2. Modify Middleware:

    In the handle method of your ProcessSlug middleware, decode the slug to handle slashes:

    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Http\Request;
    
    class ProcessSlug
    {
        public function handle(Request $request, Closure $next)
        {
            if ($request->route('page')) {
                $slug = $request->route('page');
                $decodedSlug = urldecode($slug);
                $request->route()->setParameter('page', $decodedSlug);
            }
    
            return $next($request);
        }
    }
    
  3. Register Middleware:

    Register your middleware in app/Http/Kernel.php:

    protected $routeMiddleware = [
        // ...
        'process.slug' => \App\Http\Middleware\ProcessSlug::class,
    ];
    
  4. Apply Middleware to Route:

    Apply the middleware to your route in web.php:

    Route::get('{page:slug}', [PageController::class, 'show'])
        ->middleware('process.slug');
    
  5. Controller Logic:

    In your PageController, you can now handle the slug as usual:

    namespace App\Http\Controllers;
    
    use App\Models\Page;
    use Illuminate\Http\Request;
    
    class PageController extends Controller
    {
        public function show(Page $page)
        {
            // Your logic to display the page
            return view('pages.show', compact('page'));
        }
    }
    

This approach allows you to handle slugs with slashes by decoding them before they reach your controller logic. If you need to handle more complex scenarios, you might need to adjust the middleware logic accordingly.

Please or to participate in this conversation.