Alpha
Alpha
AlphaBeta: when quoting is solved

The Basics

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:

# 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:

./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:

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

VariableExample
$REQUEST_METHODPOST
$REQUEST_TARGET/docs/search?q=mv
$REQUEST_PATH/docs/search
$REQUEST_QUERYq=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:

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

Redirects

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.

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.