Give us a second

POST ROUTES

Create routes with POST

Static and dynamic routing with POST

You have probably already understood how to create static routes with GET and dynamic routes with GET and you may be tempted to use the same principle in a POST route.

Based on how a POST request work, you should never pass variables in the URL when sending a POST request. It is possible, but the whole idea of this type of requests is that the data is sent via a form. This form is the one that will contain all the variables that the route requires.

A POST request is used to create a resource, to save something new in the database. Therefore, in principle, the URL shouldn't contain any variables. All the data should be passed inside the form (normal website) or as JSON (if it is an API)

PHP router allows you to create routes that support variables in the URL when sending a POST request, but as already said, you shouldn't do it. The following example illustrates this scenario:


// HTML form
<form action="user" method="POST">
  <input name="user_name" type="text">
  <button>Create</button>
</form>

// PHP route
post('/user', 'comp/create_user.php')

Dynamic POST route

If you really need to pass variables in the URL to create a dynamic POST route, you could do it. In the example the "form" will POST to an end-point passing number 10 as the variable:


// HTML form
<form action="user/10" method="POST">
  <input name="user_name" type="text">
  <button>Create</button>
</form>

// route
post('/user/$id' , 'something/user.php');