Skip to content

feat/fix: view() and render() cannot set HTTP status code #39

@AndreaGelmini

Description

@AndreaGelmini

Description

The view() and render() methods do not accept a status code parameter,
making it impossible to render a view with a non-200 HTTP status code.

Steps to reproduce

Trying to render a 404 view with the correct status code:

// None of these work — browser always receives 200
response()->status(404)->render('errors/404');
response()->withHeader('X-Custom-Header', 'value', true, 404)->render('errors/404');

Root cause

Internally, view() calls markup() which calls send() immediately.
By the time any status code is set, headers are already sent.

Workaround (current)

$html = app()->template()->render('errors/404', []);
response()->exit($html, 404);

This works but bypasses the response API entirely.

Proposed fix

Add an optional $code parameter (default: 200) to both view() and render():

public function view(string $view, array $data = [], int $code = 200)
{
    if (app()->template()) {
        return $this->markup(
            app()->template()->render($view, $data),
            $code
        );
    }
    // ...other engines
}

public function render(string $view, array $data = [], int $code = 200)
{
    return $this->view($view, $data, $code);
}

This is fully backward compatible since $code defaults to 200.

Use case

Essential for displaying error pages (404, 403, 500) with the correct HTTP status code
via the standard response API, without having to bypass it
by using low-level PHP functions such as http_response_code(), which may not work.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions