Dynamic Route

Dynamic Segments allow you to create routes from dynamic data when you don't know the exact segment names ahead of time. These segments can be filled in at request time or prerendered at build time.

Convention

A Dynamic Segment can be created by wrapping a folder's name in square brackets: [folderName]. For example, [id] or [slug].

Dynamic Segments are available through the Request::$dynamicParams variable in layout.php, index.php, and route.php. You can access these parameters by importing the Request class and using the $dynamicParams variable.

  • Single Route Parameters [routename]
  • Multiple Route Parameters [...routename]

Single Route Parameters

For example, a blog could include the following route app/blog/[slug]/index.php where [slug] is the Dynamic Segment for blog posts.

When a user navigates to a route with dynamic parameters, Prisma PHP captures the value from the URL and passes it to your application for processing. This allows you to create routes that respond to user input and provide a customized experience based on the value passed in the URL.

Capturing the dynamic route parameter in your route definition: app/blog/[slug]/index.php

<?php
    use Lib\Request;

    echo json_encode(Request::$dynamicParams); // Output: {"slug":"value"}
  ?>
Route Example URL params
app/blog/[slug]/index.php /blog/a { slug: 'a' }
app/blog/[slug]/index.php /blog/b { slug: 'b' }
app/blog/[slug]/index.php /blog/c { slug: 'c' }

Multiple Route Parameters

Multiple route parameters are defined by placing a [...routename] before the parameter name in the route definition. For example, src/app/api/auth[...routename]/route.php.

Capturing the dynamic route parameter in your route definition: src/app/api/auth[...routename]/route.php

<?php
    use Lib\Request;
    
    echo json_encode(Request::$dynamicParams); // Output: {"routename":["value1","value2"]}
  ?>

Catch-all Segments

Dynamic Segments can be extended to catch-all subsequent segments by adding an ellipsis inside the brackets [...folderName].

For example, app/shop/[...slug]/index.php will match /shop/clothes, but also /shop/clothes/tops, /shop/clothes/tops/t-shirts, and so on.

Route Example URL params
app/shop/[...slug]/index.php /shop/a { slug: ['a'] }
app/shop/[...slug]/index.php /shop/a/b { slug: ['a', 'b'] }
app/shop/[...slug]/index.php /shop/a/b/c { slug: ['a', 'b', 'c'] }