Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Http Constants Laravel Package

lmc/http-constants

A lightweight Laravel/PHP package that provides readable constants for HTTP status codes, helping you replace magic numbers with clear names in responses, tests, and application code. Keeps status handling more consistent and easier to understand.

View on GitHub
Deep Wiki
Context7

Getting Started

lmc/http-constants is a constants-only package: no service provider, no config file, no facade, nothing to register. In a Laravel app the entire install is:

composer require lmc/http-constants

Then import the class you need. The two classes that matter day to day are:

  • Lmc\HttpConstants\Header — header field names (Header::CONTENT_TYPE, Header::AUTHORIZATION, Header::ACCEPT, Header::X_FORWARDED_FOR, …)
  • Lmc\HttpConstants\Method — HTTP verbs (Method::GET, Method::POST, Method::PATCH, …)

A good first move is to vendor/lmc/http-constants/src/ and read the class top to bottom. It is a flat list of const declarations; scrolling it takes a minute and tells you exactly what vocabulary you get before you invent a constant that already exists or reach for a raw string that isn't covered.

The highest-value first use case is anywhere you currently hand-type a header name — middleware that sets security headers, Http::withHeaders([...]) calls, and guard clauses that inspect Authorization:

use Lmc\HttpConstants\Header;
use Lmc\HttpConstants\Method;

$request->headers->get(Header::CONTENT_TYPE);
$response->headers->set(Header::CACHE_CONTROL, 'no-store');

Http::withHeaders([Header::ACCEPT => 'application/json'])
    ->post($url, $payload);

Because the values are plain strings, this drops into Laravel's Http client, Guzzle, PSR-7/PSR-18 clients, Symfony's HeaderBag, and raw curl_setopt arrays with zero adaptation. Pick one module where header spelling bugs have actually bitten you, convert it, and treat that as the pilot before touching anything else.

Implementation Patterns

Middleware and response decoration. This is where the package pays for itself, because security and CORS headers are the classic typo surface and they fail silently — a misspelled X-Content-Type-Options simply doesn't do its job:

$response->headers->set(Header::X_CONTENT_TYPE_OPTIONS, 'nosniff');
$response->headers->set(Header::STRICT_TRANSPORT_SECURITY, 'max-age=31536000; includeSubDomains');
$response->headers->set(Header::ACCESS_CONTROL_ALLOW_ORIGIN, $origin);

Outbound HTTP clients. Configure Guzzle or Laravel's Http client once and pass constants through config arrays. Constants are valid in config because they resolve at PHP parse time, and they survive php artisan config:cache fine:

// config/services.php
'gateway' => [
    'headers' => [
        \Lmc\HttpConstants\Header::ACCEPT       => 'application/json',
        \Lmc\HttpConstants\Header::CONTENT_TYPE => 'application/json',
    ],
],

Request inspection behind proxy/load balancers. Centralize forwarded-header logic in one helper instead of scattering 'X-Forwarded-For' across controllers and form requests:

class ClientIpResolver
{
    public function resolve(Request $request): string
    {
        return $request->headers->get(Header::X_FORWARDED_FOR)
            ?? $request->ip();
    }
}

Method dispatch in custom routers and webhook receivers. Method::* reads better than literals in match and gives IDE completion plus greppability:

return match ($request->getMethod()) {
    Method::POST => $this->handleCreate($request),
    Method::PATCH, Method::PUT => $this->handleUpdate($request),
    Method::DELETE => $this->handleDelete($request),
    default => abort(405),
};

Test assertions. Assert on the constant in feature tests so a header rename is a one-line change rather than a grep-and-pray exercise:

$this->postJson('/api/orders', $payload)
    ->assertHeader(Header::CONTENT_TYPE, 'application/json');

Custom validation rules. If you validate header presence in a form request or a middleware guard, use the constant on both the read and the error message path so the two can't drift apart.

Rollout pattern: additive, never big-bang. Because the substitution is text-for-text and behaviorally identical, it is safest to introduce the package in new code only, then sweep existing literals opportunistically — during feature work, or via a scoped php-cs-fixer/Rector rule or a PHPStan baseline reduction. There is no migration, no compatibility surface, and no release train; bundling it into an existing HTTP-client or tech-debt ticket is right-sized, while funding it as its own initiative is not.

Gotchas and Tips

The package description and the code disagree — trust the code. The marketing copy talks about status codes and reason phrases; what you actually get is header field names and HTTP method names. Do not plan on Header::HTTP_OK. If you need status codes, Laravel/Symfony already give you Symfony\Component\HttpFoundation\Response::HTTP_OK and friends. Verify against src/ before designing around a constant that isn't there.

Constants don't interpolate. "Bearer {Header::AUTHORIZATION}" is a syntax error, and Header::CONTENT_TYPE inside a double-quoted string is not evaluated. Use it as an array key, a method argument, or concatenate with ..

Coverage gaps are the real adoption risk. The list is curated, not exhaustive. Vendor and X- headers (X-Request-Id, X-Correlation-ID, Idempotency-Key, Prefer) are frequently missing. Decide up front what your fallback is — raw string, or a local App\Support\HttpHeader class that extends or sits beside the package — otherwise you get a mixed convention, which is strictly worse than consistent literals. Write that rule down in the same PR that introduces the dependency.

Beware two — or three — vocabularies. Symfony ships ResponseHeaderBag and Request::HEADER_* constants, Guzzle ships RequestOptions, and PSR-7 implementations vary. If the team already leans on one of those, adding this package creates a second source of truth. Pick a canonical one per codebase and enforce it; don't let both survive "because both work."

Header names are case-insensitive on the wire, but your constants aren't. Symfony's HeaderBag normalizes on access, so headers->get(Header::CONTENT_TYPE) works regardless of how the sender cased it. But if you compare raw strings yourself ($line === 'content-type: ...'), casing will bite you. Always go through the bag, not manual explode(':') parsing.

No type safety, so static analysis only gets you so far. A constant is still a string; PHPStan/Psalm will catch a misspelled constant name and give you autocomplete, but nothing stops you from passing the right header name with an invalid value. For stricter guarantees on PHP 8.1+, a small backed enum scoped to the headers you actually use is a legitimate alternative — fewer moving parts, no third-party exposure.

Supply-chain reality check. ~25 stars and no dependents means thin maintenance. Practically this is a non-event: the artifact is inert constants with no runtime behavior, no I/O, and no autoloaded side effects. Record the exit clause — fork or copy Header.php into App\Support\Http in minutes — in your dependency register so the low-star fact is documented rather than rediscovered during an audit. Pin the major version and check the declared PHP constraint against your runtime floor when you bump PHP.

Method::* values are uppercase (GET, POST). If your code compares against $request->getMethod(), remember that's what you get in Laravel — but guard against comparing against method() output after any normalization you do yourself.

Don't expect refactor tooling to do the work. Renaming a literal into a constant is a semantic change (importing a class), not a safe regex. Use IDE inspections or a targeted Rector rule per-module; a global find-and-replace across the repo will produce imports in files that never needed them.

Zero-cost means zero signal. The package teaches nothing and abstracts nothing — a new engineer understands Header::CONTENT_TYPE in five seconds, and the value ceiling is exactly that small. Adopt it because you want a documented, greppable header convention, not because you expect an architecture win.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource