Responses
Creating Responses
Strings & Arrays
All routes and controllers should return a response to be sent back to the user's browser. Dreamfork offers various ways to return responses. The most basic response involves returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response:
Route::get('/', function() {
return 'Hello World';
});
Besides returning strings, you can also return arrays. The framework will automatically convert the array into a JSON response:
Route::get('/', function() {
return [1,2,3];
});
You can also return ORM collections from your routes or controllers, and they will be automatically converted to JSON.
Response Objects
Typically, your route actions won't just return simple strings or arrays. Instead, you might return full Framework\Http\Response instances or views.
Returning a full Response instance enables you to customize the response's HTTP status code and headers. A Response instance inherits from the Symfony\Component\HttpFoundation\Response class, providing various methods for building HTTP responses:
Route::get('/', function() {
return response('Hello World', 200);
});
ORM Models & Collections
You can also directly return ORM models and collections from your routes and controllers. Laravel will automatically convert these models and collections to JSON responses while respecting the model's hidden attributes:
use App\Models\User;
Route::get('/', function() {
return User::find(1);
});
Other Response Types
The response helper can be employed to generate various types of response instances. When the response helper is called without arguments, it returns an implementation of the Framework\Http\Routing\ResponseFactory class. This class provides several helpful methods for generating responses.
No Content Responses
To send a response with no content, you can use the noContent method, which returns a response without content and with a status of 204:
return response()->noContent();
View Responses
If you require control over the response's status and headers but also need to return a view as the response's content, use the view method:
return response()->view('welcome', $data, 200);
Of course, if you do not need to pass a custom HTTP status code or custom headers, you may use the global view helper function.
JSON Responses
The json method automatically sets the Content-Type header to application/json and converts the given array to JSON using the json_encode PHP function:
return response()->json([
'user' => User::find(1);
]);
For creating a JSONP response, you can use the jsonp method:
return response()->jsonp($request->input('callback'), [
'user' => User::find(1);
]);