Overview
Every route or controller action must return a response to the user’s browser. Laravel makes it easy to return strings, arrays, views, redirects, and JSON — all with minimal code.Basic responses
Returning a string
The simplest response is a plain string. Laravel automatically converts it into a proper HTTP response:Returning an array
Return an array and Laravel automatically converts it to a JSON response:Returning an Eloquent model or collection also produces a JSON response automatically — a convenient pattern for building simple APIs.
Returning an Eloquent model
The Response object
Use theresponse() helper when you need to control the HTTP status code or headers:
Common HTTP status codes
Returning a view
Useview() to render a Blade template. This is the most common response in a web application:
Controlling status code and headers alongside a view
Redirects
Basic redirect
Theredirect() helper returns a redirect response. It’s commonly used after form submissions to send users to a different page:
Redirecting to a named route
Use theroute() helper to redirect by route name instead of a hard-coded URL. If the URL ever changes, you only need to update the route definition:
Redirecting back
Useback() to redirect to the user’s previous location. This is common after a validation failure:
Redirect with a flash message
Usewith() to store a message in the session for the next request:
JSON responses
For APIs, return JSON explicitly withresponse()->json(). Laravel sets the Content-Type: application/json header automatically:
Returning an array or Eloquent model directly also produces JSON, but
response()->json() gives you fine-grained control over status codes and headers.Response headers
Add headers with theheader() method:
withHeaders():
Example: a complete resource controller
1
Define the routes
2
Implement the controller
Next steps
Session
Learn how to store data across requests using Laravel’s session.