Adding Publish Tags to Laravel Package Resources
When a Laravel package includes files that users might want to customize, publish tags let them copy selected files into their application.…
When Laravel code sends a request to an external API, Laravel’s HTTP client returns a response with the server’s status code, headers, and body. These details show whether the request succeeded and what the server sent. For 4xx and 5xx status responses, including 404 and 500, Laravel returns the former as a response by default, while a connection failure can occur before any response arrives.
Use response methods to inspect the status and content, check whether the status indicates success, and validate decoded JSON before using it. The examples follow Laravel’s documented HTTP client behavior. Check the documentation for the Laravel version installed in your project.
A request such as Http::get() returns an Illuminate\Http\Client\Response object. Inspect the response with its methods:
use Illuminate\Support\Facades\Http;
$response = Http::get('https://api.example.com/users/42');
$status = $response->status();
$contentType = $response->header('Content-Type');
$rawBody = $response->body();
status() returns the numeric HTTP status code. header($name) returns the header with that name, and headers() returns all headers as an array. body() returns the response body as a string. This helps when the server sends unexpected content, such as an HTML error page instead of JSON. Laravel documents these and other methods in its HTTP client reference.
For JSON responses, json() decodes the body, object() returns the decoded data as an object, and collect() returns it as a Laravel collection. You can also use array access to read a JSON value by key, as in $response['name']. When you do not know the API’s response format or it varies, decode the body into a variable and inspect its contents before using them.
Laravel does not throw an exception automatically when a server returns a 4xx or 5xx status. Check the status with these methods: successful() matches 2xx responses; failed() matches client or server errors. To distinguish the error class, use clientError() for 4xx responses or serverError() for 5xx responses.
if ($response->successful()) {
// Handle a successful 2xx response.
} elseif ($response->clientError()) {
// Handle a 4xx response.
} elseif ($response->serverError()) {
// Handle a 5xx response.
} elseif ($response->redirect()) {
// Handle a redirect when the code needs to distinguish it.
}
Use successful() to check for success in general. ok() matches exactly 200, so it does not match other successful statuses such as 201 Created or 204 No Content. Laravel also provides methods for specific statuses, including created(), noContent(), notFound(), and tooManyRequests(). These methods do not treat a 3xx response as a 2xx success or a 4xx/5xx failure. Use redirect() or check status() when your code needs to handle redirects. See Laravel’s documentation for response status checks.
json() returns mixed, which means the decoded value could be an array, a single value such as a string or number, or a different structure from the one your code expects. A successful status does not guarantee that the body contains the fields your code needs. Check the status, decide how to handle invalid JSON, and validate the decoded value and required fields.
Laravel’s json() method accepts flags, which are options that control how it decodes the body. Passing PHP’s JSON_THROW_ON_ERROR flag makes invalid JSON raise a JsonException that your code can handle:
use Illuminate\Support\Facades\Http;
use JsonException;
use UnexpectedValueException;
$response = Http::get('https://api.example.com/users/42');
if (! $response->successful()) {
throw new UnexpectedValueException(
"Unexpected HTTP status: {$response->status()}"
);
}
try {
$data = $response->json(flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
throw new UnexpectedValueException(
'The API returned invalid JSON.',
previous: $e
);
}
if (! is_array($data)) {
throw new UnexpectedValueException('Expected a JSON object or array.');
}
$userId = $data['data']['id'] ?? null;
if ($userId === null) {
throw new UnexpectedValueException('The response did not include data.id.');
}
The code that uses this API must check for the required structure. Laravel does not perform this check for the external API. The Response API reference documents the JSON method’s arguments for selecting a key, providing a default value, and setting decoding flags.
To read an optional top-level value, pass its key to json() and provide a fallback:
$name = $response->json('name', 'Unknown');
Use a fallback only if your code should treat a missing value as "Unknown". A default supplies a value, but it does not confirm that the rest of the response has the expected structure.
Use the status-check methods when your code needs to handle different statuses directly. Call throw() when you want a 4xx or 5xx response to raise an exception:
$response = Http::get('https://api.example.com/users/42');
$response->throw();
$data = $response->json();
For a client or server error, throw() raises an Illuminate\Http\Client\RequestException. The exception includes the response, which your code can inspect. If throw() does not raise an exception, it returns the response. You can also pass a callback to throw() to run code before it raises the exception. Laravel describes these behaviors in the Laravel HTTP client documentation.
A connection failure may occur before Laravel receives an HTTP response, so you have no status or body to inspect. Catch Illuminate\Http\Client\ConnectionException around the request:
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
try {
$response = Http::get('https://api.example.com/users/42');
} catch (ConnectionException $e) {
// Handle the failure to connect.
}
Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.
Take a look at vroni.com