# Controllers

## Introduction

Instead of defining all of your request handling logic as functions in your route files, you may wish to organise it in controllers. A controller is a file in `app/Http/Controllers` that defines functions with a common prefix:

```bash
# app/Http/Controllers/PostController.sh

PostController::show() {
  local post comments
  post=$(Post::find "$1") || abort 404
  comments=$(Comment::all | where post_id = "$1")
  view posts.show post="$post" comments="$comments" title="Post #$1"
}
```

Generate one with Artisan:

```bash
./sail artisan make:controller UserController
```

## Requests

### Input

Query string and form fields are parsed into the `REQUEST` associative array. Read them with `request`, which takes an optional default:

```bash
name=$(request name)
page=$(request page 1)
```

Form bodies are only parsed when the `Content-Type` is `application/x-www-form-urlencoded`. JSON bodies are in `$REQUEST_BODY`, for `jq`.

### The request line and headers

| Variable | Example |
|---|---|
| `$REQUEST_METHOD` | `POST` |
| `$REQUEST_TARGET` | `/docs/search?q=mv` |
| `$REQUEST_PATH` | `/docs/search` |
| `$REQUEST_QUERY` | `q=mv` |
| `${REQUEST_HEADERS[user-agent]}` | `curl/8.5.0` |

Header names are lowercased with `${key,,}`, so you never have to guess the capitalisation.

## Responses

Anything a controller prints is the response body. The status and headers are set with functions:

```bash
status 201
header Content-Type application/json
Post::all | toJson
```

### Redirects

```bash
redirect "/posts/$id"
```

### Aborting

`abort` sets the status, renders `resources/views/errors/{status}.blade.sh` if there is one, and exits. Exiting is fine: the `EXIT` trap sends the response.

```bash
post=$(Post::find "$1") || abort 404
```

> [!WARNING]
> `abort` only works in the request's own process. Inside `$( )`, it exits the subshell, not the request, so call it outside command substitutions.
