The request and the response in Masonite work together to form a well formed response that a browser can read and render. The Request class is used to fetch any incoming cookies, headers, URL's, paths, request methods and other incoming data.
Although both the request and response classes have headers and cookies, in most instances, when fetching cookies and headers, it should be fetched from the Request class. When setting headers and cookies it should be done on the response class.
To get cookies you can do so simply:
This will fetch the cookie from the incoming request headers.
You can also set cookies on the request:
Note that setting cookies on the request will NOT return the cookie as part of the response and therefore will NOT keep the cookie from request to request.
Although both the request and response classes have headers and cookies, in most instances, when fetching cookies and headers, it should be fetched from the Request class. When setting headers and cookies it should be done on the response class.
To get a request header you can do so simply:
You can also set a header on the request class:
Note that setting headers on the request will NOT return the header as part of the response.
You can get the current request URI:
You can get the current request method:
You can check if the current path contains a glob style schema:
You can get the current subdomain from the host:
You can get the current host:
Inputs can be from any kind of request method. In Masonite, fetching the input is the same no matter which request method it is.
To fetch an input we can do:
If an input doesn't exist you can pass in a default:
To fetch all inputs from request we can do:
Or we can only fetch some inputs:
To fetch all inputs from request we can do:
If your input is a dictionary you can access nested data in two ways. Take this code example:
You can either access it normally:
Or you can use dot notation to fetch the value for simplicity:
You can also use a * wildcard to get all values from a dictionary list.:
Route parameters are parameters specified in a route and captured from the URL:
If you have a route like this:
You can get the value of the @user_id
parameter like this:
As a convenient way to fetch the user, you can do so directly on the request class if a user is logged in:
If the user is not authenticated then this will be set to None
You can fetch the IP address (ipv4) from which the request has been made by adding the IpMiddleware
to the HTTP middlewares of the project:
Then you can use the ip()
helper:
IP address is retrieved from various HTTP request headers in the following order:
HTTP_CLIENT_IP
HTTP_X_FORWARDED_FOR
HTTP_X_FORWARDED
HTTP_X_CLUSTER_CLIENT_IP
HTTP_FORWARDED_FOR
HTTP_FORWARDED
REMOTE_ADDR
The first non-private and non-reserved IP address found by resolving the different headers will be returned by the helper.
The headers used and their order can be customized by overriding the IpMiddleware
and changing the headers
attribute: