HTTP Response
The Response class provides an object-oriented way to create and send HTTP responses, including setting content, headers, status codes, and redirects.
Creating Responses
Basic response creation:
use Spark\Http\Response;
// Create a new response
$response = new Response('Hello World', 200);
// Using the helper function
$response = response('Hello World', 200);
Setting Response Content
// Set content
$response->setContent('New content');
// Append content
$response->write('Additional content');
JSON Responses
// Simple JSON response
$response->json(['status' => 'success', 'data' => $result]);
// JSON with custom status code
$response->json(['error' => 'Not found'], 404);
// Using helper
return response()->json(['message' => 'Created'], 201);
Redirects
// Basic redirect
$response->redirect('/new-location');
// Redirect back to previous page
$response->back();
// Using redirect helper
redirect('/dashboard');
// Redirect with flash data
return response()
->with('message', 'Please login first')
->redirect('/login');
Headers & Status Codes
// Set status code
$response->setStatusCode(404);
// Set header
$response->setHeader('Content-Type', 'text/xml');
// Set multiple headers
$response
->setHeader('Cache-Control', 'no-cache')
->setHeader('X-Custom', 'Value');
Session Flash Data
// Flash data for next request
$response->with('message', 'Operation successful');
$response->with('alert', 'Profile updated');
// Typically used with redirects
return response()
->with('status', 'Welcome back!')
->redirect('/dashboard');
Sending Responses
// Send the response to client
$response->send();
// The response will automatically send when returned from controller
return $response;
Response Helpers
// response() helper examples
return response('Hello World', 200);
return response()->json($data);
return response()->redirect('/');
// redirect() helper shortcut
return redirect('/home');
Best Practice: In controllers, simply return the response object rather than
calling
send() directly - the framework will handle sending it automatically.