Requests and Responses

Updated on Jul 11, 2024

It is time to discuss requests and responses in the Laravel framework, two fundamental concepts that drive any Laravel application. We mentioned them briefly at the beginning of this tutorial when we listed some important terminology and will not discuss them in more detail. Let's begin with requests.

You Will Read About:

section

Requests

You have probably heard this word a lot when it comes to applications or programming. What exactly is a request, though? Typically, in the context of programming – and Laravel itself, a request is the interaction an application receives from a user. It is called a request because this interaction requests a response from the application based on the input from the user. A basic example of this is when you open a website. Websites are web applications, so when you open one, it receives a request to present the homepage to your browser. It then sends a response to that request, and the cycle repeats each time a user takes an action. Another way to think of this is to imagine that each time you click on a button on a website, this request-response cycle is triggered. The mouse click is the request.

In programming, the word "request" most commonly refers to HTTP requests since those are the ones most applications use and rely on to function. The same applies to Laravel. As we mentioned, requests are fundamental to Laravel's operation, and it handles them rather elegantly. It is a six-step process on a most basic level, so let's break it down and look at how exactly Laravel handles HTTP requests.

  1. User Interaction - For an application to receive a request, a user typically has to interact with it. There are exceptions to that, but we will keep it simple for our purposes. Let's say you click the login button on a website;
  2. HTTP Request - After you have clicked the button, the application's logic kicks in. First comes the HTTP request. It carries information about the interaction you performed: accessing data, inputting data, requesting a URL, and so on. In our case, we are requesting the URL for the login page;
  3. Routing and Controller Handling - Routes are the entry points for your application. In Laravel, the index.php file is typically in the public directory. From there, the application sends the request to the correct controller, depending on the routes defined in the web.php or api.php files: web routes or API routes, respectively. When the application locates the correct request controller, it triggers the corresponding methods. Methods are the actions the application can perform. Additionally, the request can also be encapsulated in the Request object since it contains some convenient methods for accessing input data, files, cookies, or other request-related information;
  4. Controller Logic - The controller executes the logic specified within it. As mentioned before, the controller is the mediator between the user and the application's functionalities. In our case, clicking on the login button would trigger the controller to seek out the appropriate View and possibly a database connection, as well as authentication for the user;
  5. Response Generation - Once the controller method has completed its task (gathered all the necessary data from the database, found the correct View, and so on), it generates the HTTP response. Laravel is excellent when it comes to this because it will convert all the gathered data into the HTTP format, so no additional coding is required to accomplish that;
  6. Response Return - Once the response is generated, it is returned to the user's browser and rendered. For us, that would be the login screen with the username and password and any other functionality it may have. 

Middleware can increase the number of steps a request takes until it returns a response. We have mentioned it in our index of important terminology. Simply put, though, middleware is code that can be inserted throughout the request-response sequence and can alter how it acts. For instance, in our example, middleware would handle user authentication if the provided user had the correct permissions to log in.

That is the chain of events that requests go through. As you can see, it ends with the return of a response, which we will discuss next.

section

Responses

As you read above, the response is the final step of the request-response cycle. That makes sense! Now, let's explain what a response is.

To begin with, the easiest way to understand a response is to think of what you see on your screen when you interact with a given application or website. When you click a button, the change that occurs is the application's response: whether you are taken to a new page or the current page updates in real-time are both examples of a response.

When talking about responses, we typically mean HTTP responses, as they are the most commonly used ones, including in Laravel. To return a response, use the return model and then place the desired function in parenthesis after it. For example, return view('welcome');. That line of code returns the welcome view when the request is made to that response. There are several common HTTP response types, and they are below.

  • response() - This general-purpose method is best suited for creating simple text responses. Put any text you want between the parentheses, and it will appear when the response is requested. For example: return response('Hello, World!');
  • view() - This type of HTTP response will invoke any view you put between the parentheses. Remember, Views are stored in the resources/views directory and can either be Blade templates or plain Views;
  • json() - A response of this type is used when building APIs or returning a request from a JavaScript-based application. Here is an example of what a response of this type would look like: return response()->json(['message' => 'Data retrieved successfully']);
  • redirect() - As the name suggests, this HTTP response will redirect the user to a different URL when this response is returned. This can stop users from accessing a specific page and redirecting them to another. It is also very handy for any sort of form submissions, logins, logouts, and so on to direct the user to the correct page after the action. Here is a quick example of what that could look like.
     // Action: user authenticated
Route::post('/signin', function () {
// Use the response() helper function to create a redirect response:
    return response()->redirect('/dashboard');
});
  • download() - Another self-explanatory response. This one will cause the user to download a file when requested. If you have seen a download button on a website, then it is likely evoking this type of response when the file is sent to your browser, and your computer consequently. That is what a response of this type can look like in Laravel. It literally instructs the application to provide the specified file to your browser for download;
Route::post('/download', function () {
            return response()->download('file_path/file_name.zip');
});
  • file() - A variation of the download() response; instead, this will instruct the user's browser to display the specified file or download it if possible. The code for it looks like this: return response()->file($pathToFile);

To round out our look at responses in Laravel, we will discuss response headers and status codes. Firstly, the response headers. In Laravel, you can assign custom headers to your responses by using the header() method. You can use the header() method and a line of code like this to set up a single header.

return response('Hello')->header('Content-Type', 'text/plain');

As you can see, this header sets the content type of our Hello response to text/plain. You can use code like this to set up multiple headers.

return response('')->withHeaders([
    'Content-Type' => 'text/plain',
    'X-Custom-Header' => 'Custom Value',
]);

Use the withHeaders() methods and specify all the headers you wish within square brackets, separated by a new line. A list of all available HTTP headers and an explanation of their functions can be found here.

And finally, let's take a look at status codes within Laravel. A status code is a three-digit number accompanying a response to indicate the result of a request. You might be familiar with status code 404 if you have ever tried to access a page that does not exist. That is precisely what the code means: the resource you are looking for is not found on the server. You can use the response() function to set up a status code. Here is an example.

return response('Not Found')->setStatusCode(404);

Since there are many status codes, we recommend you take a look at this article, where they are all outlined and ready for use.

That concludes our look at responses in Laravel. As you can see, they are an important part of the framework's mechanism. Without them, we would be clicking away on our computers, and nothing would change.

On this page...