# Laravel Bash > The PHP framework for web artisans, now without the PHP. A working satire: routing, Eloquent, Blade, queues, events, broadcasting and scheduling, built from Bash and the Unix tools already on your server. This file concatenates every documentation page in sidebar order. Prefer /llms.txt when you only need an index, or /docs/{page}.md for a single page. --- # Release Notes Source: https://laravel-bash.mrstebo.co.uk/docs/releases.md # Release Notes ## Introduction Laravel Bash is the newest member of the Laravel family, after PHP, [Rust](https://laravel.com/blog/introducing-laravel-for-rust) and [Go](https://laravel.com/blog/introducing-laravel-for-go). It runs on the shell that is already installed on every server you have ever deployed to. > [!NOTE] > Laravel Bash is not affiliated with or endorsed by Laravel. ## Versioning Scheme Laravel Bash is in **Alpha**. Everything in these docs works, and anything in them may change. The beta will ship once quoting has been solved, so Alpha is likely to last a while. `./artisan --version` tells you which one you have. ## Support Policy | Version | Bash | Released | Bug Fixes Until | |---|---|---|---| | Alpha | 5.1 or later | 6 December 2026 | Whenever someone opens an issue | Bash 5.1 is the minimum because Laravel Bash uses `wait -n -p`, which arrived in 5.1. macOS ships Bash 3.2 from 2007, so on a Mac you'll want [Sail](/docs/sail). ## Laravel Bash Alpha ### Every request is a process `./artisan serve` doesn't serve anything itself. It asks `socat` to listen on port 8000 and fork a new copy of `bootstrap/handle` for every connection. Nothing is shared between requests, like PHP since 1995. Read more in the [request lifecycle](/docs/lifecycle). ### Eloquent pipelines Models run SQL, and everything after that is a pipeline of small programs over tab-separated text: ```bash Post::all | where status = published | orderBy votes desc | take 3 ``` Read more in the [Eloquent documentation](/docs/eloquent). ### Queues, events and broadcasting Jobs are files that workers claim with `mv`. Events are `kill -USR1`. Broadcasting is `tail -F` streamed as Server-Sent Events. All of them can be watched live in the [examples](/examples). ### ./artisan dev One command starts the server, four queue workers, the event listener, the scheduler and the log, and stops them all when one of them stops. ### Upgrading from PHP There is no upgrade path from Laravel PHP. There is barely an upgrade path from Laravel Bash. --- # Installation Source: https://laravel-bash.mrstebo.co.uk/docs/installation.md # Installation ## Meet Laravel Bash Laravel Bash is a web application framework with expressive, elegant syntax, as long as your idea of elegant includes `"${@:2}"`. It gives you routing, controllers, an ORM, templates, validation, queues, events, broadcasting and a task scheduler, built from the small Linux programs that are already on your server. ### Why Laravel Bash? - **Zero dependencies.** Apart from Bash 5, `socat`, `sqlite3`, `jq`, `awk`, `sort`, `join`, `flock`, `timeout` and Docker. - **Share-nothing.** Every request is a brand new process, so there is no state to leak between requests, or anywhere else. - **Proven technology.** Most of the programs Laravel Bash uses are older than PHP. ## Creating a Laravel Bash Application ### Installing Docker Laravel Bash needs GNU tools and Bash 5.1 or later. macOS ships BSD tools and Bash 3.2, so Laravel Bash runs in Docker with [Sail](/docs/sail). Install [Docker Desktop](https://www.docker.com/products/docker-desktop/) or [OrbStack](https://orbstack.dev) first. ### Creating the application ```bash git clone https://github.com/mrstebo/laravel-bash.git example-app cd example-app cp .env.example .env ./sail up -d ./sail artisan migrate --seed ``` Then open [localhost:8000](http://localhost:8000). The container runs `./artisan dev`, which starts the web server, four queue workers, the event listener and the scheduler, so the [examples](/examples) work straight away. > [!NOTE] > There is no Composer. There is no installer. There is `git clone`, which is how all software was installed before 2012. ## Initial Configuration Configuration lives in `.env`, which is loaded line by line when the framework boots: ```bash APP_NAME="Laravel Bash" APP_ENV=local APP_DEBUG=true DB_CONNECTION=sqlite QUEUE_WORKER_SLEEP=0.5 QUEUE_JOB_TIMEOUT=60 ``` Read a value anywhere with `config`: ```bash config APP_NAME # Laravel Bash config MAIL_MAILER log # log, the default ``` ### Why not `source .env`? The obvious way to load a `.env` file in Bash is `set -a; source .env; set +a`. That runs your `.env` file as code, so `APP_NAME=$(rm -rf ~)` does exactly what it says. It also overrides real environment variables, which [phpdotenv](https://github.com/vlucas/phpdotenv) doesn't do. So `env::load` reads the file one line at a time, matches each line against `^([A-Z_][A-Z0-9_]*)=(.*)$`, strips the quotes and comments, and only exports a key if it isn't already set. Real environment variables win, so this works: ```bash DB_CONNECTION=pgsql ./sail artisan migrate ``` ## Databases SQLite is the default, like Laravel 11 and later. Set `DB_CONNECTION=pgsql` to use the Postgres container that Sail starts. See [Database: Getting Started](/docs/database). ## Next Steps Read about the [request lifecycle](/docs/lifecycle) to see what actually happens when a browser asks for a page, then [the binaries](/docs/binaries) that make it all work. --- # Directory Structure Source: https://laravel-bash.mrstebo.co.uk/docs/structure.md # Directory Structure ## Introduction The default Laravel Bash application structure will look very familiar, because it was copied. The difference is that every file ends in `.sh`. ## The Root Directory | Directory | What's in it | |---|---| | `app/` | Your controllers, form requests, models, jobs, events and listeners. Every `.sh` file in here is sourced when the framework boots. | | `bootstrap/` | `app.sh` boots the framework. `handle` is the program socat runs for each request. | | `database/` | Migrations (plain `.sql` files), seeders and the SQLite database file. | | `docs/` | These pages, as Markdown. | | `framework/` | What would be `vendor/laravel/framework`: routing, Eloquent, Blade, queues and the rest, plus `markdown.awk`. | | `resources/views/` | Blade templates, which are Bash files that print HTML. | | `routes/` | `web.sh` for routes, `console.sh` for the schedule. | | `storage/` | Logs, the queue folders, the event log and the broadcast log. | | `tests/` | The bats test suite. | ## The Root Files - `artisan` is the command line. It's a Bash script, like it always secretly wanted to be. - `sail` wraps `docker compose`. Laravel Sail was always a Bash script, so this one is the real thing. - `compose.yaml` and `Dockerfile` describe the `app` and `pgsql` containers. ## The Storage Directory | Path | Used by | |---|---| | `storage/logs/laravel.log` | `Log::info` and friends | | `storage/queue/pending/` | Jobs waiting to run | | `storage/queue/processing/` | Jobs a worker has claimed | | `storage/queue/failed/` | Jobs that failed or timed out | | `storage/events/events.log` | Event payloads, for the listener to read | | `storage/broadcasts/broadcasts.log` | Everything broadcast, followed by `tail -F` | | `storage/framework/*.lock` | `flock` locks for the scheduler | > [!NOTE] > Everything in `storage/` is a plain text file. If you want to know what the framework is doing, `cat` it. --- # Deployment Source: https://laravel-bash.mrstebo.co.uk/docs/deployment.md # Deployment ## Introduction When you're ready to deploy your Laravel Bash application to production, there are some important things you can do to make sure it runs as efficiently as possible. There aren't many, because there isn't much of it. ## Server Requirements The image in the `Dockerfile` has everything: Bash 5, the GNU tools, `socat`, `sqlite3`, `jq` and [tini](https://github.com/krallin/tini). Whatever runs it needs to give the app: - **One long-running container.** `./artisan dev` starts the server, the queue workers, the event listener and the scheduler, and keeps them running. - **A database that survives restarts.** Either Postgres, or SQLite on a disk mounted at `storage/`. The queue folders, the broadcast log and the rate limiter's counts live in `storage/` too, but losing them in a restart costs no more than a few jobs that hadn't run yet. - **Exactly one instance.** Queue workers claim jobs with `mv`, events wake the listener with `pkill`, and broadcasts follow a file with `tail -F`. All of that assumes one machine. A second instance would have its own disk and its own processes, and neither would know about the other. - **Responses that stream**, for [broadcasting](/docs/broadcasting). - **A health check**, which `/up` answers. ## The Image Locally, compose mounts the project into the container. In production, the image is the app, so the `Dockerfile` copies it in, and `.dockerignore` leaves out `.git`, `.env`, the local database and everything in `storage/`. `tini` is PID 1. It passes `SIGTERM` on to `./artisan dev`, which stops the others and exits, and it reaps the processes `socat` forks for each request: ```dockerfile ENTRYPOINT ["tini", "-s", "--"] CMD ["./artisan", "dev"] ``` When `./artisan dev` starts, it makes any `storage/` folders that are missing, because a new, empty volume hides the folders the image came with. Then it waits up to a minute for the database to answer, and if it has never been migrated, it runs `migrate --seed` before anything else starts. ## Configuration There's no `.env` in production. Set real environment variables instead: ```bash APP_ENV=production APP_DEBUG=false # error pages without the stack trace APP_URL=https://laravel-bash.mrstebo.co.uk # canonical URL for sitemap, Open Graph, llms.txt DB_CONNECTION=pgsql # with DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, DB_PASSWORD PGSSLMODE=require # psql reads this itself TRUSTED_PROXY_HEADER=X-Envoy-External-Address # see Rate Limiting in the routing docs MAX_CHILDREN=32 # requests at once; the rest wait to be accepted APP_DEMO=true # run demo:reset every hour ``` `MAX_CHILDREN` goes to `socat` as `max-children`. Each open Server-Sent Events stream holds one until its tab closes, so leave room for them. ## Health Checks Like Laravel, Laravel Bash has a health route at `/up`. It answers `200 Application up` when the database does, and `500` when it doesn't. ## Streaming Through a Proxy Proxies close connections that go quiet. Broadcasting streams send a `: ping` comment line after 15 seconds without an event, which browsers ignore. Set `BROADCAST_HEARTBEAT` to change the interval. ## SQLite on a Volume To keep everything in one container, put the SQLite database on the same volume as everything else: ```bash DB_SQLITE_PATH=storage/database.sqlite ``` A volume can only be mounted by one container at a time, so deploys have to stop the old container before they start the new one. Expect half a minute of downtime on every deploy. ## Northflank The repository has a [Northflank](https://northflank.com) template in `northflank.json`. It creates a project with: - a Postgres addon; - a secret group that hands the addon's connection details to the app as `DB_HOST`, `DB_PORT`, `DB_DATABASE`, `DB_USERNAME` and `DB_PASSWORD`; - a combined service that builds the `Dockerfile` on every push to `main`, except for changes to files the app doesn't serve, like the README and the tests. With nothing on the service's disk worth keeping, deploys are rolling: the new container starts, passes its health check, and only then does the old one stop. With GitOps switched on for the template, Northflank reads the template from the repository and runs it again whenever `northflank.json` changes on `main`. There's no deploy pipeline. --- # Request Lifecycle Source: https://laravel-bash.mrstebo.co.uk/docs/lifecycle.md # Request Lifecycle ## Introduction When using any tool in the "real world", you feel more confident if you understand how it works. This page follows one request from the moment it arrives on port 8000 to the moment its process exits, which is about twenty milliseconds later. ## Lifecycle Overview ### First steps: socat `./artisan serve` runs one command and becomes it: ```bash exec socat TCP-LISTEN:8000,reuseaddr,fork EXEC:bootstrap/handle ``` `socat` listens on port 8000. For each connection, `fork` makes a copy of socat, and `EXEC` runs `bootstrap/handle` with the TCP socket as its **stdin** and **stdout**. The handler doesn't know about networks: it reads a request from stdin and writes a response to stdout, like any other Unix program. > [!NOTE] > Every request is a separate process with nothing shared, which is how PHP has worked since 1995. Laravel Octane exists to keep one process alive between requests. Laravel Bash has gone the other way. ### The HTTP kernel `bootstrap/handle` sources `bootstrap/app.sh`, which turns on strict mode, loads `.env` and sources every file in `framework/`, `app/` and `routes/`. Then `http::handle` runs: ```bash exec 3>&1 4>&2 # keep the socket on fd 3, and the server log on fd 4 http::read_request # the request line, the headers, then the body BODY_FILE=$(mktemp) trap http::send EXIT # send the response when this process exits, however it exits trap 'http::exception $? "$BASH_COMMAND" $LINENO' ERR exec 1>"$BODY_FILE" # from here on, anything printed is the response body router::dispatch ``` The trick is file descriptors. The socket is copied to fd 3 for safe keeping, then stdout is pointed at a temporary file. Controllers just print HTML. When the process exits, the `EXIT` trap measures the file for `Content-Length`, writes the status line and headers to the socket, then `cat`s the body after them. ### Reading the request HTTP/1.1 is a text protocol, which is the only reason any of this is possible: ```text POST /posts HTTP/1.1 Host: localhost:8000 Content-Type: application/x-www-form-urlencoded Content-Length: 46 title=Hello&body=A+body+that+is+long+enough. ``` The request line and headers are read with `read -r`, one line at a time, until a blank line. Each line ends in `\r\n`, so `${line%$'\r'}` takes the `\r` off. The body has no newline at the end, so it's read with `read -N "$length"`, in the C locale, because `Content-Length` counts bytes and Bash otherwise counts characters. ### Routing The router compares the path with each route's regex using `[[ =~ ]]` and calls the first match, with the captured parameters as arguments. See [Routing](/docs/routing). ### Sending the response When the controller returns, the process exits, and `http::send` runs: ```text HTTP/1.1 200 OK content-type: text/html; charset=utf-8 x-powered-by: Laravel Bash content-length: 2817 connection: close ``` Then a line goes to the server log on fd 4, and a `RequestHandled` event goes to the [Pulse](/pulse) page. ## Streaming responses Server-Sent Events can't be buffered to a file, because they never end. `http::stream` writes the headers straight to fd 3 and marks the response as streamed, so the `EXIT` trap leaves it alone. See [Broadcasting](/docs/broadcasting). --- # The Binaries Source: https://laravel-bash.mrstebo.co.uk/docs/binaries.md # The Binaries ## Introduction Laravel Bash is mostly other people's programs. Every feature is one of the channels Unix gives every process, and a program that knows how to use it. This page lists them, and why we picked each one over the alternatives. ## How Programs Talk Every Unix process gets the same handful of ways to communicate, and every Laravel concept turns out to be one of them: | Channel | What it carries | Laravel Bash uses it for | |---|---|---| | Arguments | Input, once, at the start | Job arguments, route parameters | | Environment variables | Configuration, inherited by children | `.env`, `DB_CONNECTION` | | stdin / stdout | A stream of text | Requests, responses, Eloquent pipelines | | stderr | Diagnostics | Stack traces, the log | | Exit codes | One number, 0 to 255 | Exceptions, validation, failed jobs | | Signals | A doorbell with no message | Events, stopping workers | | Files and renames | Anything, durably | Queues, the event log, broadcasts | | Sockets | Bytes between machines | HTTP | ## The Binaries | Binary | Job in Laravel Bash | Why this one | |---|---|---| | `socat` | The web server | `nc` has three incompatible versions (OpenBSD, GNU and BusyBox), and Bash's `/dev/tcp` can connect but can't listen | | `sqlite3`, `psql` | The database drivers | Both print tab-separated text with `-separator` and `--field-separator` | | `awk` | `where`, `only`, the Markdown renderer | A whole language for columns of text, in every POSIX system | | `sort` | `orderBy` | `-t` and `-k` sort by a field; `-g` sorts numbers; `-s` keeps ties in order | | `head` | `take` | It exits early, and SIGPIPE stops everything upstream | | `cut` | `pluck` | The fastest way to take one column | | `join` | `withCount` | A real relational join, on sorted text | | `uniq -c` | Counting relations | `GROUP BY` and `COUNT(*)` in one flag | | `column -t` | Tinker's tables | Lines everything up | | `jq` | JSON | Quoting JSON by hand is how security advisories are written | | `mv` | Claiming jobs | A rename is atomic on one filesystem | | `timeout` | Job timeouts | Exits with 124, so we know why a job died | | `flock` | `withoutOverlapping` | `-n` takes the lock or gives up at once | | `tail -F` | Broadcasting | Follows a file, even after it's rotated | | `grep --line-buffered` | Filtering broadcasts | Without it, events arrive late in 4 KB lumps | | `pkill`, `pgrep` | Events, Horizon | Find processes by their command line | | `mktemp` | Response bodies, concurrency results | Unique files nobody else will write to | | `sed` | Migrations, stripping colours | Search and replace in a stream | | `shellcheck`, `bats` | The test suite | Larastan and Pest, respectively | ## Builtins Before Binaries Starting a program is the expensive part of shell scripting: a `fork` and an `exec` cost far more than anything Bash does on its own. So wherever Bash has a builtin that does the job, Laravel Bash uses it: - `printf '%(%F %T)T'` instead of `date`, for log timestamps. - `${#value}` and `[[ =~ ]]` instead of `wc` and `grep`, for [validation](/docs/validation). - `${s// [!NOTE] > The rule is: use a builtin when one value is involved, and a program when a stream is. `sed` beats a Bash loop over 10,000 lines. A Bash substitution beats `sed` on one string. --- # Routing Source: https://laravel-bash.mrstebo.co.uk/docs/routing.md # Routing ## Basic Routing The most basic Laravel Bash routes accept a method, a URI and the name of a function, which is a very simple and expressive way of defining routes and behaviour without complicated routing configuration files: ```bash route GET /greeting greeting greeting() { echo 'Hello World' } ``` ### The Default Route Files All routes are defined in `routes/web.sh`, which is sourced when the framework boots. Because every request is a new process, it's sourced for every request too. Route caching is not available, and also not needed, because there is nothing to cache it in. ### Available Router Methods ```bash route GET /posts PostController::index route POST /posts PostController::store route PUT /posts/{post} PostController::update route DELETE /posts/{post} PostController::destroy ``` ## Route Parameters ### Required Parameters Parameters are wrapped in braces, and passed to your function as arguments, in order: ```bash route GET /posts/{post}/comments/{comment} show_comment show_comment() { local post=$1 comment=$2 echo "Post $post, comment $comment" } ``` > [!NOTE] > ShellCheck will tell you that `{post}` looks like brace expansion. It isn't: Bash only expands braces that contain a comma or a range, like `{a,b}` or `{1..3}`. ### How matching works `route` turns each `{param}` into the regex `([^/]+)` and stores the result. For each request, `router::dispatch` tries them in order with `[[ =~ ]]`, which puts the captured groups in `BASH_REMATCH`: ```bash if [[ $REQUEST_PATH =~ ${ROUTE_REGEXES[i]} ]]; then "${ROUTE_ACTIONS[i]}" "${BASH_REMATCH[@]:1}" fi ``` If the path matches but the method doesn't, the response is a `405`. If nothing matches, it's a `404`. ## Controllers as functions Bash allows `::` in function names, so controllers keep their Laravel names with no extra work: ```bash route GET /posts/{post} PostController::show ``` See [Controllers](/docs/controllers). ## Listing Your Routes ```bash ./sail artisan route:list ``` ```text GET / ........................................... welcome GET /examples ................................... examples GET /dashboard .................................. DashboardController::index GET /posts ...................................... PostController::index GET /posts/create ............................... PostController::create POST /posts ...................................... PostController::store throttle:10,1 GET /posts/{post} ............................... PostController::show ``` ## Middleware Middleware goes after the action, as `name:arguments`. It runs before the action, and stops the request by calling `abort`: ```bash route POST /posts PostController::store throttle:10,1 ``` Each middleware is a function called `middleware::`, in `framework/middleware.sh` or anywhere else that gets sourced. Its arguments arrive as one string, `10,1`, the way Laravel passes them. ### Rate Limiting `throttle:,` allows each client `` requests every `` minutes, then answers `429 Too Many Requests` with a `Retry-After` header. Each request appends one byte to a file under `storage/framework/throttle`, and the size of the file is the count: ```bash printf . >> "$prefix-$window" count=$(stat -c %s "$prefix-$window") ``` A one-byte write with `O_APPEND`, which is what `>>` asks for, is atomic, so two requests at the same moment can't both read 9 and both write 10. There's nothing to lock. Behind a proxy, every request seems to come from the proxy. Set `TRUSTED_PROXY_HEADER` to the header your proxy fills in with the real address, and only if the proxy replaces that header rather than passing on whatever the visitor sent: ```bash TRUSTED_PROXY_HEADER=X-Envoy-External-Address ``` ## Not available Named routes, route groups, model binding and signed URLs. Pull requests are welcome, but they will need to be written in Bash. --- # Controllers Source: https://laravel-bash.mrstebo.co.uk/docs/controllers.md # 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. --- # Views & Blade Source: https://laravel-bash.mrstebo.co.uk/docs/blade.md # Views & Blade ## Introduction Blade is the simple, yet powerful templating engine included with Laravel. In Laravel Bash, Blade templates are Bash files that print HTML with heredocs. A heredoc already expands `$variables` and `$(commands)`, so the templates were compiled before you wrote them. ```bash # resources/views/greeting.blade.sh cat <Hello, $(e "$name")

This page was rendered by process $$.

HTML ``` ## Rendering Views ```bash view greeting name="Taylor" ``` Each `key=value` becomes a local variable in the view. The dotted name `posts.show` means `resources/views/posts/show.blade.sh`. ### Passing models When a value holds exactly one row of query results (a header line and one data line), the view gets an associative array instead of text: ```bash view posts.show post="$(Post::find 1)" ``` ```bash cat <$(e "${post[title]}") HTML ``` ## Displaying Data ### Escaping `{{ $name }}` is `$(e "$name")`. `e` escapes `&`, `<`, `>`, `"` and `'` with parameter expansion, so it doesn't start a program: ```bash e() { local s=${1-} s=${s//&/"&"} s=${s///">"} s=${s//\"/"""} s=${s//\'/"'"} printf '%s' "$s" } ``` > [!WARNING] > The replacements are in quotes for a reason. Since Bash 5.2, an unquoted `&` in a replacement means "the text that matched", like in `sed`. Without the quotes, `&` becomes `&amp;`, which is not what anyone wants. ### Raw output `{!! $html !!}` is just `$html`. Be careful, as you would be with Blade. ## Layouts Every view is wrapped in `resources/views/layouts/app.blade.sh`, which prints `$slot` where the page goes. Views in `layouts/` and `partials/` aren't wrapped. ## Loops There is no `@foreach`. There is `while`, and `next_row`, which reads the header line first, then fills an associative array with each row: ```bash declare -A post while next_row post; do cat < $(e "${post[title]}") ${post[votes]} HTML done <<< "$posts" ``` ### Empty fields Splitting a row with `IFS=$'\t' read` looks right, but tab counts as whitespace, and `read` merges runs of whitespace. A row with an empty field in the middle shifts every field after it one column to the left. So `next_row` swaps each tab for byte `0x1F`, the ASCII *unit separator*, which `IFS` treats literally. It has been waiting since 1963 for someone to use it. ## Why not envsubst? `envsubst` replaces `$VARIABLES` in a template, which sounds perfect. But it only sees exported variables, it can't run functions like `e`, and it comes from gettext, which isn't always installed. A `sed`-based engine means escaping every value twice, once for HTML and once for `sed`, and getting one of them wrong is an injection. Heredocs need neither. --- # Validation Source: https://laravel-bash.mrstebo.co.uk/docs/validation.md # Validation ## Introduction Laravel Bash provides a single function to validate your application's incoming data, and it uses Bash builtins only: `${#value}` for lengths and `[[ =~ ]]` for patterns. ## Validation Quickstart ```bash PostController::store() { if ! validate title "required|min:3|max:80" \ body "required|min:20" \ status "required|in:published,draft"; then status 422 view posts.create title="New post" return fi local id id=$(Post::create title="$(request title)" body="$(request body)" status="$(request status)") redirect "/posts/$id" } ``` `validate` takes pairs of a field and its rules. It returns 0 if everything passes, and 1 if anything fails, which is what `if !` is for. ### Displaying the errors Messages are put in the `ERRORS` associative array, keyed by field, and `error` prints the first one in a `

`. `old` prints the submitted value back, escaped: ```bash cat < $(error title) HTML ``` ## Form Requests For anything bigger than a field or two, move the rules into a form request in `app/Http/Requests`: ```bash # app/Http/Requests/StorePostRequest.sh StorePostRequest::rules() { cat <<'RULES' title required|min:3|max:80 body required|min:20 status required|in:published,draft RULES } ``` One field per line, then its rules. Generate one with `./sail artisan make:request StorePostRequest`. Then in the controller: ```bash PostController::store() { if ! form_request StorePostRequest; then status 422 view posts.create title="New post" return fi local id local -a data validated data id=$(Post::create "${data[@]}") redirect "/posts/$id" } ``` `validated data` fills the array `data` with `field=value` for every field that was validated, like `$request->validated()`. Anything else in the request is left out, so a form that also posts `votes=1000000` doesn't get to set the votes. The model's [`fillable`](/docs/eloquent#mass-assignment) list is the second line of defence. ## Available Validation Rules | Rule | Passes when | Built with | |---|---|---| | `required` | It isn't empty or only whitespace | `${value//[[:space:]]/}` | | `min:n` | It's at least *n* characters | `${#value}` | | `max:n` | It's at most *n* characters | `${#value}` | | `numeric` | It's a number | `[[ =~ ^-?[0-9]+(\.[0-9]+)?$ ]]` | | `email` | It has an `@` and a dot after it | `[[ =~ ]]` | | `alpha_dash` | Letters, numbers, `-` and `_` only | `[[ =~ ]]` | | `in:a,b` | It's one of the listed values | `[[ ",a,b," == *",$value,"* ]]` | | `regex:pattern` | It matches an extended regex | `[[ =~ ]]` | > [!NOTE] > `min` and `max` count characters, not bytes, because Bash's `${#value}` is locale-aware. `max:3` accepts `🐚🐚🐚`. ## Why not grep? `grep -E` could check every rule, but it's a separate program, and each one costs a `fork` and an `exec`. A form with ten fields and three rules each would start thirty processes. `[[ =~ ]]` uses the same POSIX extended regular expressions without leaving Bash. That also means no `\d`: extended regexes don't have it. Write `[0-9]`. --- # Error Handling Source: https://laravel-bash.mrstebo.co.uk/docs/errors.md # Error Handling ## Introduction When you start a new Laravel Bash project, error and exception handling is already configured for you, by `set -Eeuo pipefail` and two traps. ## Strict mode `bootstrap/app.sh` turns on Bash's strict mode before anything else: | Option | Meaning | |---|---| | `-e` | Exit when a command fails, like an uncaught exception | | `-E` | Run the `ERR` trap inside functions too | | `-u` | Using a variable that was never set is an error, like `strict_types` for typos | | `-o pipefail` | A pipeline fails if any part of it fails, not just the last one | > [!WARNING] > `set -e` is ignored inside anything being tested: an `if` condition, either side of `&&` or `||`, and after `!`. A function that would fail is fine when called as `if my_function`, and every command inside it carries on regardless. This is documented, and still surprises everyone. ## The Exception Handler Every request sets a trap on `ERR`, which runs when any command fails: ```bash trap 'http::exception $? "$BASH_COMMAND" $LINENO' ERR ``` `http::exception` sets the status to 500, logs the failure, and renders `errors.500` with a stack trace. The stack trace comes from `caller`, a builtin that prints the line, function and file of each frame: ```text 34 whoops routes/web.sh 24 router::dispatch framework/routing.sh 139 http::handle framework/http.sh 5 main bootstrap/handle ``` See it at [/whoops](/whoops). ## HTTP Exceptions ```bash abort 404 abort 403 ``` `abort` renders `resources/views/errors/{status}.blade.sh` if it exists, then exits. The `EXIT` trap sends the response. ## Exit codes are exceptions In Laravel, a failing function throws. In Bash, it returns a number other than 0, and the caller decides what to do: ```bash post=$(Post::find "$1") || abort 404 ``` 0 means success, and is the only value of "true" that is falsy everywhere else in computing. --- # Logging Source: https://laravel-bash.mrstebo.co.uk/docs/logging.md # Logging ## Introduction Laravel Bash writes logs to `storage/logs/laravel.log`, in the same format as Laravel: ```text [2026-12-04 21:14:03] local.INFO: Created post #9 [2026-12-04 21:14:11] local.ERROR: Job [ProcessPodcast 14] failed with exit code 1 ``` ## Writing Log Messages ```bash Log::debug "Checking the cache" Log::info "Created post #$id" Log::warning "No event listener is running" Log::error "Job [$job] timed out" ``` The timestamp comes from `printf '%(%F %T)T'`, which is a Bash builtin, so logging never starts `date`: ```bash Log::write() { local level=$1; shift printf '[%(%F %T)T] %s.%s: %s\n' -1 "$APP_ENV" "$level" "$*" >> storage/logs/laravel.log } ``` ## Tailing Log Messages Laravel Pail tails your logs from the command line. So does `tail`: ```bash ./sail shell tail -F storage/logs/laravel.log ``` `./artisan dev` already does this, and prefixes each line with `log`. > [!NOTE] > Use `tail -F`, not `tail -f`. Lower case follows the open file, so after log rotation it watches a file nobody writes to any more. Upper case follows the name, and reopens it. ## Why not logger? `logger` sends messages to syslog, which is what system services should do. In a container, there's usually no syslog to send them to. --- # Artisan Console Source: https://laravel-bash.mrstebo.co.uk/docs/artisan.md # Artisan Console ## Introduction Artisan is the command line interface included with Laravel. In Laravel PHP, it's a command line interface to the framework. In Laravel Bash, the whole framework was a command line interface all along. ```bash ./sail artisan list ``` ## Running the Application ### ./artisan dev `composer run dev` starts the server, a queue worker, Pail and Vite together, using the `concurrently` npm package. `./artisan dev` does the same with `&`: ```text server │ INFO Server running on [http://0.0.0.0:8000]. queue │ INFO Processing jobs from the [default] queue with 4 worker(s). events │ INFO Listening for events (PID 15). Send one with: kill -USR1 15 schedule │ INFO Running scheduled tasks every minute. log │ [2026-12-05 00:12:12] local.INFO: Emailed the customer: order #5 has shipped ``` Each one is a real `./artisan` process, started in the background with its output sent through a [process substitution](https://www.gnu.org/software/bash/manual/html_node/Process-Substitution.html) that adds the coloured prefix: ```bash "$@" > >(dev::prefix "$name" "$colour") 2>&1 3>&- & DEV_PROCESSES[$!]=$name ``` Because the prefixer is a process substitution rather than the end of a pipe, `$!` is the PID of the command itself. Then `wait -n` waits for whichever finishes first and, like `concurrently --kill-others`, stops the rest. It's the container's default command, so `./sail up -d` runs it. ## Tinker Tinker is an interactive Bash with the framework loaded: ```bash ./sail artisan tinker ``` ```text Laravel Bash Tinker. Bash 5.2.15. Try: Post::all | take 3 | table > Post::all | where status = published | only id title votes | take 3 | table id title votes 1 Introducing Laravel Bash 342 2 Why every request gets its own process 128 3 Eloquent is a pipeline 256 ``` It's `bash --rcfile` with an rc file that sources `bootstrap/app.sh`, then switches strict mode off, because in a REPL a typo shouldn't end the session. To run one line and exit: ```bash ./sail artisan tinker --execute='Post::all | count' ``` ## Writing Commands A command is a function called `artisan::` followed by the command name, with the colons swapped for underscores. Artisan finds it with `declare -F`: ```bash artisan::podcasts_publish() { local id=${1:?Usage: ./artisan podcasts:publish } dispatch ProcessPodcast "$id" artisan::info "Podcast $id queued." } ``` ```bash ./sail artisan podcasts:publish 42 ``` ### Output helpers | Function | Prints | |---|---| | `artisan::info "Done."` | ` INFO Done.` on a cyan background | | `artisan::error "Oops."` | ` ERROR Oops.` on a red background, to stderr | | `artisan::line "Database" "sqlite"` | `Database ................ sqlite` | ## Generating Files ```bash ./sail artisan make:controller UserController ./sail artisan make:model Comment ./sail artisan make:job SendNewsletter ./sail artisan make:seeder UserSeeder ./sail artisan make:request StorePostRequest ``` The stubs are heredocs. `make:model` works out the table name with `sed -E 's/([a-z0-9])([A-Z])/\1_\2/g'` and `${table,,}`, then adds an `s`. It does not know about irregular plurals. ## Available Commands | Command | Description | |---|---| | `about` | Basic information about your application | | `dev` | Run the server, queue, events, scheduler and log together | | `serve` | Serve the application with socat | | `tinker` | Interact with your application | | `inspire` | Display an inspiring quote | | `route:list` | List all registered routes | | `migrate` | Run the migrations, `--seed` to seed | | `migrate:fresh` | Drop all tables and migrate again | | `queue:work` | Process jobs, `--workers=N` | | `queue:failed` / `queue:retry` | List or retry failed jobs | | `horizon` | Show the workers and job counts | | `event:listen` | Listen for events | | `schedule:run` / `schedule:work` / `schedule:list` | The scheduler | | `test` | shellcheck, then bats | Some of them can be run from the browser on the [Artisan example](/artisan). --- # Broadcasting Source: https://laravel-bash.mrstebo.co.uk/docs/broadcasting.md # Broadcasting ## Introduction In many modern web applications, WebSockets are used to implement realtime, live-updating user interfaces. Laravel Bash uses Server-Sent Events instead, because a WebSocket starts with an HTTP upgrade, a SHA-1 hash and a binary frame format, and Server-Sent Events are just text that never ends. ```text event: OrderShipped data: {"order_id":"1"} ``` The browser side is the built-in `EventSource`, which reconnects by itself: ```html ``` ## Broadcasting Events ```bash broadcast orders OrderShipped "$(json order_id=1)" ``` `broadcast` appends one line to `storage/broadcasts/broadcasts.log`: the channel, the event name and the data, separated by tabs. The data must be JSON on one line, so build it with `json`, which lets `jq` do the quoting: ```bash json order_id=1 note='He said "hi"' # {"order_id":"1","note":"He said \"hi\""} ``` Events with a `broadcastOn` function are broadcast automatically when they're fired. See [Events](/docs/events). ## Receiving Broadcasts Every `GET /broadcasting/{channel}` request is a process that runs this until the browser goes away: ```bash tail -n 0 -F "$BROADCAST_LOG" \ | grep --line-buffered "^${channel}"$'\t' \ | while IFS=$'\t' read -r _ event data; do printf 'event: %s\ndata: %s\n\n' "$event" "$data" done >&3 ``` - `tail -n 0 -F` starts at the end of the file, prints each new line as it's written, and keeps going if the file is rotated. - `grep` keeps the lines for this channel. - The loop turns each line into an SSE message and writes it to fd 3, the socket. Open the [Orders](/orders) page in two tabs and ship something. Both tabs are separate processes, following the same file. > [!WARNING] > Without `--line-buffered`, nothing happens for ages, then everything happens at once. When its output is a pipe rather than a terminal, `grep` saves it up in 4 KB blocks, so events sit in its buffer until enough of them arrive. `--line-buffered` sends each line on immediately. For programs without that flag, `stdbuf -oL` does the same job. ## The pulse channel `/broadcasting/pulse` streams every channel at once, wrapped in one JSON object per message. The [Pulse](/pulse) page uses it. See [Pulse](/docs/pulse). ## Channels | Channel | Events | Sent by | |---|---|---| | `orders` | `OrderShipped` | `event OrderShipped` | | `queue` | `JobQueued`, `JobProcessing`, `JobProcessed`, `JobFailed`, `JobsRetried` | `dispatch` and the workers | | `events` | `EventDispatched`, `ListenerHandled` | `event` and the listener | | `artisan` | `CommandFinished` | The Artisan example and the scheduler | | `requests` | `RequestHandled` | Every request | ## Why not WebSockets? Reverb speaks the Pusher protocol over WebSockets. To do that in Bash, we'd need to read the `Sec-WebSocket-Key` header, append a fixed GUID, hash it with `sha1sum`, convert the hex to binary and then to base64, and then read and write frames with masked binary payloads and variable-length headers, using `od` and `printf '\x..'`. It is possible. We have chosen life. SSE is one-way, server to browser, which is all broadcasting needs. The browser talks back with ordinary form posts. > [!NOTE] > Browsers allow only six HTTP/1.1 connections to one host, and every open SSE stream uses one. With seven live tabs open, the seventh waits. --- # Concurrency Source: https://laravel-bash.mrstebo.co.uk/docs/concurrency.md # Concurrency ## Introduction Sometimes you need to run several slow tasks that don't depend on each other. Laravel's `Concurrency` facade runs them in child processes. So does Laravel Bash, which is the one time the two implementations agree. ## Running Concurrent Tasks ```bash count_posts() { sleep 1; Post::count; } count_comments() { sleep 1; Comment::count; } fetch_weather() { sleep 1; echo "Drizzle, 7°C"; } mapfile -d '' -t results < <( Concurrency::run count_posts count_comments fetch_weather ) echo "${results[2]}" # Drizzle, 7°C ``` Three tasks that take a second each take one second in total. See it on the [Dashboard](/dashboard). ## How It Works ```bash Concurrency::run() { local dir task pid i=0 j local -a pids=() dir=$(mktemp -d) for task in "$@"; do "$task" > "$dir/$i" & pids+=("$!") i=$((i + 1)) done for pid in "${pids[@]}"; do wait "$pid" || { rm -rf "$dir"; return 1; } done for ((j = 0; j < i; j++)); do cat "$dir/$j" printf '\0' done rm -rf "$dir" } ``` 1. `&` starts each task in a child process. `$!` is its PID. 2. A child can't set its parent's variables, so each one writes to its own file in a private `mktemp -d` folder. 3. `wait "$pid"` waits for each one and returns its exit code. A failed task is a thrown exception. 4. The results come back in order, each followed by a NUL byte. `mapfile -d ''` splits on NUL. ### Why NUL? Results can contain newlines, tabs and spaces, but they can't contain a NUL byte, because Bash variables can't hold one. That makes it the only separator that's always safe. `find -print0 | xargs -0` uses it for the same reason. ## Why not xargs -P or parallel? | Tool | Why not | |---|---| | `xargs -P 4` | It runs programs, not Bash functions, and the outputs come back interleaved in whatever order they finish. | | GNU `parallel` | Excellent, and written in Perl. We have a strict no-Perl policy, for now. | | `coproc` | Bash only lets you have one coprocess at a time, and warns if you start a second. | --- # Events Source: https://laravel-bash.mrstebo.co.uk/docs/events.md # Events ## Introduction Laravel's events provide a simple observer pattern implementation, allowing you to subscribe and listen for various events that occur within your application. Laravel Bash's events are signals, and signals are a doorbell, not a letterbox. ## Registering Listeners Listeners are registered in `app/Providers/EventServiceProvider.sh`: ```bash listen OrderShipped SendShipmentNotification ``` A listener is a function called `handle`, which gets the event's payload as JSON: ```bash # app/Listeners/SendShipmentNotification.sh SendShipmentNotification::handle() { local order_id order_id=$(jq -r .order_id <<< "$1") Log::info "Emailed the customer: order #$order_id has shipped (listener PID $$)" } ``` ## Dispatching Events ```bash event OrderShipped order_id=1 ``` Listeners run in a separate, long-lived process, which `./artisan dev` starts: ```bash ./sail artisan event:listen ``` ## How It Works ### Ringing the doorbell `event` appends the event to `storage/events/events.log`, then sends `SIGUSR1` to every process whose command line matches `artisan event:listen`: ```bash printf '%s\t%s\n' "$name" "$payload" >> "$EVENT_LOG" pkill -USR1 -f 'artisan event:listen' ``` ### Answering the door The listener sets a trap for the signal, then waits: ```bash trap event::drain USR1 while :; do sleep 60 & wait $! done ``` When `SIGUSR1` arrives, Bash runs `event::drain`, which reads every line of the log it hasn't seen yet, with `mapfile -s` to skip the ones it has, and calls each listener. > [!NOTE] > Bash only runs a trap when the current command finishes. If the loop were just `sleep 60`, an event could wait up to a minute. `wait` is different: a signal interrupts it straight away. So the loop runs `sleep` in the background and waits for it. ### Why the payload goes in a file Signals carry no data at all, there are only two for our own use (`USR1` and `USR2`), and two of the same signal arriving close together can be merged into one. So the signal can't be the event. It just means "go and look", and the listener reads everything new since it last looked. Two merged signals still mean the listener looks once and finds both events. ## Broadcasting Events An event is broadcast if it has a `broadcastOn` function, which is Laravel Bash's `ShouldBroadcast`: ```bash OrderShipped::broadcastOn() { echo orders } ``` See [Broadcasting](/docs/broadcasting). Every event and every listener that handles one is also broadcast on the `events` channel, so you can watch the doorbell ring on [Pulse](/pulse). --- # Queues Source: https://laravel-bash.mrstebo.co.uk/docs/queues.md # Queues ## Introduction While building your web application, you may have some tasks, such as processing an uploaded podcast, that take too long to perform during a typical web request. Laravel Bash's queue driver is the filesystem, and its lock is `mv`. ```text storage/queue/pending/ jobs waiting to run storage/queue/processing/ jobs a worker has claimed storage/queue/failed/ jobs that failed or timed out ``` ## Creating Jobs ```bash ./sail artisan make:job ProcessPodcast ``` A job is a function called `handle`, which gets the arguments it was dispatched with: ```bash # app/Jobs/ProcessPodcast.sh ProcessPodcast::handle() { local id=$1 sleep 1 if (( id % 7 == 0 )); then echo "Podcast $id is corrupt." >&2 return 1 fi Log::info "Processed podcast $id" } ``` Returning anything other than 0 fails the job. ## Dispatching Jobs ```bash dispatch ProcessPodcast 42 ``` `dispatch` writes the job to a temporary file, then moves it into `pending/`: ```bash printf -v id '%s-%s-%05d' "${EPOCHREALTIME/./}" "$BASHPID" "$RANDOM" tmp=$(mktemp "$QUEUE_PATH/.dispatch.XXXXXX") printf '%q' "$job" > "$tmp" printf ' %q' "$@" >> "$tmp" mv "$tmp" "$QUEUE_PATH/pending/$id.job" ``` - The file name starts with the time in microseconds, so `pending/` sorts oldest first, and the queue is first in, first out. - `printf %q` quotes each argument so that Bash can read it back exactly, spaces and all. - Writing elsewhere and moving the file in means a worker never sees half a job. ## Running the Queue Worker ```bash ./sail artisan queue:work --workers=4 ``` ### Claiming a job Each worker loops over `pending/` and tries to move each job into `processing/`: ```bash for file in "$QUEUE_PATH"/pending/*.job; do claimed="$QUEUE_PATH/processing/${file##*/}" mv "$file" "$claimed" 2> /dev/null || continue # another worker got there first queue::run "$worker" "$claimed" done ``` Four workers will see the same file at the same moment and all try to move it. A rename within one filesystem is a single `rename(2)` system call, which happens completely or not at all, so exactly one `mv` succeeds. The other three get "No such file or directory", and move on to the next job. > [!WARNING] > This only works when `pending/` and `processing/` are on the same filesystem. Across filesystems, `mv` copies and then deletes, which is not atomic. Don't put the queue on NFS. ### Running a job Each job runs in its own `./artisan queue:handle` process, under `timeout`: ```bash timeout "${QUEUE_JOB_TIMEOUT:-60}" ./artisan queue:handle "$file" ``` If it exits with 0, the file is deleted. Otherwise it's moved to `failed/`, with the exit code in its name. `timeout` exits with `124`, so a timed-out job is easy to spot: ```text 1796429649235062-141-28704.exit-1.job 1796429650114522-152-01733.exit-124.job ``` ### Supervising the workers `queue:work` starts the workers in the background, then supervises them with `wait -n -p`, which waits for any one child to exit and says which: ```bash while :; do wait -n -p pid Log::warning "Worker ${worker_of[$pid]} (PID $pid) exited. Starting a replacement." queue::worker "${worker_of[$pid]}" & done ``` Kill a worker with `kill -9` and a new one takes its place. That's what Supervisor is for in Laravel PHP. ## Dealing With Failed Jobs ```bash ./sail artisan queue:failed ./sail artisan queue:retry ``` `queue:retry` moves every file in `failed/` back into `pending/`, without the exit code. ## Trying It The [Queues](/queues) example has buttons that dispatch jobs, and shows every worker claiming and finishing them as it happens. Open it in two tabs. ## Why not a FIFO? `mkfifo` makes a named pipe, which looks like a queue. But when several workers read from one pipe, they can each get half a line. Writes are only atomic up to `PIPE_BUF` (4096 bytes on Linux), and a pipe forgets everything when nobody's reading, so jobs dispatched while the workers are down are lost. Files stay where you put them. --- # Task Scheduling Source: https://laravel-bash.mrstebo.co.uk/docs/scheduling.md # Task Scheduling ## Introduction Laravel's scheduler lets you define your schedule in code, then needs one cron entry on your server. That cron entry was always a line of shell, so it works as it is: ```bash * * * * * cd /var/www/html && ./artisan schedule:run >> /dev/null 2>&1 ``` ## Defining Schedules Schedules are defined in `routes/console.sh`: ```bash schedule inspire everyMinute schedule queue:retry hourly ``` | Frequency | Runs | |---|---| | `everyMinute` | Every minute | | `everyFiveMinutes` | When the minute is divisible by 5 | | `hourly` | At minute 0 | | `daily` | At midnight | ```bash ./sail artisan schedule:list ``` ## Running the Scheduler Locally Without cron, `schedule:work` runs the schedule every minute. `./artisan dev` starts it for you. ```bash ./sail artisan schedule:work ``` It sleeps until the start of the next minute, rather than for 60 seconds, which would drift by however long the tasks took: ```bash sleep $(( 60 - $(printf '%(%s)T' -1) % 60 )) ``` > [!NOTE] > The minute is read with `printf '%(%M)T'`, which gives `08` at eight minutes past. Bash reads numbers with a leading zero as octal, and `08` is not a valid octal number, so the scheduler breaks at 8 and 9 minutes past every hour. `$((10#$minute))` forces base 10. ## Preventing Task Overlaps Every scheduled command runs under `flock -n`, which is `withoutOverlapping()`: ```bash flock -n "storage/framework/schedule-inspire.lock" ./artisan inspire ``` `flock` takes a lock on the file for as long as the command runs. `-n` means don't wait: if a previous run still holds the lock, give up and skip this one. The kernel releases the lock when the process exits, even if it crashes, so there are no stale lock files to clean up. ## Output Each scheduled command's output is broadcast on the `artisan` channel, so it appears on the [Artisan](/artisan) example every minute. --- # Getting Started Source: https://laravel-bash.mrstebo.co.uk/docs/database.md # Database: Getting Started ## Introduction Almost every modern web application talks to a database. Laravel Bash talks to two, through their command line clients, which both agree to print tab-separated text with a header row. That's the only thing the rest of Eloquent needs. | Connection | Client | How it's asked for tabs | |---|---|---| | `sqlite` | `sqlite3` | `-separator $'\t' -header` | | `pgsql` | `psql` | `--no-align --field-separator=$'\t' --pset=footer=off` | ### Configuration SQLite is the default, and keeps everything in `database/database.sqlite`. To use the Postgres container that Sail starts, set `DB_CONNECTION=pgsql` in `.env`, or for one command: ```bash DB_CONNECTION=pgsql ./sail artisan migrate --seed ``` ```bash DB_HOST=pgsql DB_PORT=5432 DB_DATABASE=laravel DB_USERNAME=sail DB_PASSWORD=password ``` ## Running SQL Queries ```bash DB::select 'SELECT id, title FROM posts WHERE votes > 100' # rows, with a header line DB::statement 'SELECT COUNT(*) FROM posts' # no header: one value ``` ### Quoting There are no prepared statements on the command line, so values are quoted with `DB::quote`, which doubles single quotes: ```bash DB::quote "O'Brien" # 'O''Brien' ``` > [!WARNING] > Tabs and newlines are the field and row separators, so `DB::quote` turns them into spaces. A post body can't contain a newline. This is a known limitation, and also a feature, depending on who's asking. ### Inserting ```bash id=$(DB::insert posts title="Hello" body="World") ``` `DB::insert` builds the column and value lists, and ends the statement with `RETURNING id`, which SQLite has supported since 3.35. ## The SQLite busy timeout Every request is a separate process, and so is every worker, so several `sqlite3` processes can write to the same file at once. SQLite locks the whole database during a write, and by default anyone else gives up straight away with `database is locked`. Laravel Bash passes `-cmd '.timeout 5000'`, so they wait up to five seconds instead. ## Connecting to the Databases ```bash ./sail sqlite # sqlite3 database/database.sqlite ./sail psql # psql in the pgsql container ``` --- # Migrations & Seeding Source: https://laravel-bash.mrstebo.co.uk/docs/migrations.md # Migrations & Seeding ## Introduction Migrations are like version control for your database. In Laravel Bash, they're `.sql` files in `database/migrations`, run in the order their names sort. ```bash ./sail artisan migrate ./sail artisan migrate --seed ./sail artisan migrate:fresh --seed ``` ## Writing Migrations ```sql -- database/migrations/2026_12_04_000001_create_posts_table.sql CREATE TABLE posts ( id {{increments}}, title VARCHAR(80) NOT NULL, body TEXT NOT NULL, status VARCHAR(20) NOT NULL DEFAULT 'draft', votes INTEGER NOT NULL DEFAULT 0, created_at {{timestamp}} ); ``` Most SQL is the same in SQLite and Postgres. The parts that aren't are written as placeholders, and the schema grammar fills them in with `sed`: | Placeholder | SQLite | Postgres | |---|---|---| | `{{increments}}` | `INTEGER PRIMARY KEY AUTOINCREMENT` | `BIGSERIAL PRIMARY KEY` | | `{{timestamp}}` | `TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP` | `TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP` | ```bash DB::grammar() { case $DB_CONNECTION in sqlite) sed -e 's/{{increments}}/INTEGER PRIMARY KEY AUTOINCREMENT/g' ... ;; pgsql) sed -e 's/{{increments}}/BIGSERIAL PRIMARY KEY/g' ... ;; esac } ``` ### Which migrations have run Like Laravel, a `migrations` table records each one, and `migrate` skips those it finds there. ### Dropping everything `migrate:fresh` deletes the SQLite file, or on Postgres drops and recreates the `public` schema, then migrates from the start. ## Seeding Seeders live in `database/seeders`, one per file, and each one is a function called `::run`. `db:seed` and `--seed` run `DatabaseSeeder`, which runs the others with `call`, in order: ```bash # database/seeders/DatabaseSeeder.sh DatabaseSeeder::run() { call PostSeeder CommentSeeder } ``` ```bash # database/seeders/PostSeeder.sh PostSeeder::run() { local title status votes body while IFS='|' read -r title status votes body; do Post::create title="$title" status="$status" votes="$votes" body="$body" > /dev/null done <<'ROWS' Introducing Laravel Bash|published|342|Laravel now runs on PHP, Rust, Go and the shell you already have. Queues with mv|published|401|A rename is atomic, so four workers can share one folder. ROWS } ``` ```text INFO Seeding database. PostSeeder ............................................... RUNNING PostSeeder ............................................. 31ms DONE CommentSeeder ............................................ RUNNING CommentSeeder .......................................... 41ms DONE ``` To run one seeder on its own: ```bash ./sail artisan db:seed --class=PostSeeder ``` ### Writing seeders ```bash ./sail artisan make:seeder UserSeeder ``` This creates `database/seeders/UserSeeder.sh`. Add it to `DatabaseSeeder::run` with `call UserSeeder`. There's no need to register it anywhere else, because `bootstrap/app.sh` sources every file in `database/seeders`. > [!NOTE] > Laravel resolves seeders from its service container, so they can ask for dependencies in their constructors. Laravel Bash has no classes and no container. It looks functions up by name when they're called, so `call` only needs the name, and `declare -F` checks that it exists first. There are no factories. There is a heredoc, and a pipe character you hope nobody uses in a title. --- # Getting Started Source: https://laravel-bash.mrstebo.co.uk/docs/eloquent.md # Eloquent: Getting Started ## Introduction Laravel includes Eloquent, an object-relational mapper. Laravel Bash includes Eloquent, a text-relational pipeline. A model runs SQL, and everything after that is small programs passing tab-separated text to each other, with a header row at the top: ```bash Post::all | where status = published | orderBy votes desc | take 3 ``` ## Defining Models ```bash # app/Models/Post.sh model Post posts fillable title body status votes attributes status=draft votes=0 casts votes=integer hasMany comments Comment post_id ``` `model` defines `Post::all`, `Post::find`, `Post::count`, `Post::create` and `Post::table` with `eval`. Generate one with `./sail artisan make:model Post`. A model file reads like a class body: `model` names the model, and the lines after it describe it, until the next `model`. ### Mass assignment `fillable` lists the columns that `create` may set, like `$fillable`. Anything else is an error, not silently ignored: ```text $ ./sail artisan tinker --execute='Post::create title=Hi body=… id=1' Add [id] to the fillable property to allow mass assignment on [Post]. ``` > [!WARNING] > This matters more here than in Laravel. The keys you pass to `create` become column names in the `INSERT`, and only the values are quoted. `fillable` is what keeps a posted field name out of your SQL. Use it with [form requests](/docs/validation#form-requests), which only pass on the fields they validated. ### Default attribute values `attributes` sets values for columns that `create` isn't given, like `$attributes`. ### Attribute casting `casts` checks and converts values on the way into the database, like `$casts`: | Cast | Accepts | Stores | |---|---|---| | `integer` | `-?[0-9]+` | the number | | `boolean` | `1`, `true`, `on`, `yes`, `0`, `false`, `off`, `no` and empty | `1` or `0` | Anything else is an error. On the way out, everything is text again, because text is what flows through the pipes. ## Retrieving Models ```bash Post::all # every row, ordered by id Post::find 1 || abort 404 # one row, or exit code 1 Post::count # a number ``` ## Building Queries Every helper reads rows on stdin and writes rows on stdout, so they chain with `|` in any order: | Helper | Example | Built with | |---|---|---| | `where` | `where votes '>' 100` | `awk` | | `orderBy` | `orderBy votes desc` | `sort -t $'\t' -k` | | `take` | `take 3` | `head` | | `skip` | `skip 10` | `tail -n +` | | `first` | `first` | `head` | | `only` | `only id title` | `awk` | | `pluck` | `pluck title` | `cut -f` | | `count` | `count` | `wc -l` | | `withCount` | `withCount comments` | `uniq -c` and `join` | | `table` | `table` | `column -t` | | `toJson` | `toJson` | `jq` | ```text > Post::all | where status = published | only id title votes | take 3 | table id title votes 1 Introducing Laravel Bash 342 2 Why every request gets its own process 128 3 Eloquent is a pipeline 256 ``` ### where `where` is a short `awk` program. It finds the column's number in the header row, then compares that field on every other row. `=` and `!=` compare text; `>`, `<`, `>=` and `<=` compare numbers; `like` is a case-insensitive substring. ```bash Post::all | where title like bash ``` > [!NOTE] > Quote `'>'` and `'<'`. Unquoted, they're redirections, and Bash will create a file called `100` in your project. ### orderBy `orderBy` takes the header off with `read`, then hands the rest to `sort`. If the first value looks like a number, it adds `-g` to sort numerically, so `9` comes before `10`. `-s` keeps rows with equal values in their original order. ### Why there's no select The helper that keeps only some columns is called `only`, because `select` is a Bash keyword: it builds numbered menus. ## Lazy Collections Laravel's lazy collections only load what they need. In Laravel Bash, every query is lazy, thanks to `SIGPIPE`: ```bash Post::all | where status = published | take 3 ``` `take 3` is `head -n 4` (the header, then three rows). After four lines, `head` exits. The next time `awk` writes to the pipe, nobody is reading it, and the kernel sends `awk` a `SIGPIPE`, which ends it. The same happens to `sqlite3` behind it. The rest of the table is never read. ## Inserting Models ```bash id=$(Post::create title="Hello" body="World" status=draft) ``` `create` fills in the default `attributes`, checks every key against `fillable`, applies the `casts`, then runs one `INSERT … RETURNING id` and prints the id. --- # Relationships Source: https://laravel-bash.mrstebo.co.uk/docs/eloquent-relationships.md # Eloquent: Relationships ## Introduction Database tables are often related to one another. In Laravel Bash, those relationships are joined with `join`, a program from 1979 that does relational joins on sorted text files and that almost nobody has heard of. ## One to Many ```bash # app/Models/Post.sh model Post posts hasMany comments Comment post_id ``` `hasMany` records the relationship: the related model and its foreign key. ### Querying the relationship ```bash Comment::all | where post_id = 1 ``` ## Counting Related Models ```bash Post::all | withCount comments | orderBy comments_count desc | take 3 | table ``` ```text id title comments_count 1 Introducing Laravel Bash 3 4 Queues with mv 3 3 Eloquent is a pipeline 2 ``` `withCount` adds a `comments_count` column, which is a `LEFT JOIN ... GROUP BY` in SQL. In Laravel Bash it's two pipelines and `join`: ```bash join -t $'\t' -a 1 -e 0 -o auto \ <(sort -t $'\t' -k 1,1) \ <(Comment::all | pluck post_id | sort | uniq -c | awk -v OFS='\t' '{ print $2, $1 }') ``` 1. The posts come in on stdin, sorted by id. 2. `pluck post_id | sort | uniq -c` counts the comments for each post: that's the `GROUP BY`. 3. `join` matches the two on their first field. `-a 1` keeps posts with no comments, which is the `LEFT`. `-e 0` fills the missing count with 0. > [!WARNING] > `join` needs both sides sorted the same way, as text. Sorted as numbers, `10` comes after `9`, but `join` expects it to come after `1`, and quietly drops rows. That's why there's a plain `sort` on each side, then `orderBy` afterwards. ## Set Operations `comm` compares two sorted lists and prints what's only in the first, only in the second, or in both. It's `whereIn` and `whereNotIn`: ```bash # Posts with no comments comm -23 <(Post::all | pluck id | sort) <(Comment::all | pluck post_id | sort -u) ``` --- # Getting Started Source: https://laravel-bash.mrstebo.co.uk/docs/testing.md # Testing: Getting Started ## Introduction Laravel Bash is built with testing in mind. ShellCheck is our Larastan, and [bats](https://github.com/bats-core/bats-core) is our Pest: ```bash ./sail test ``` `./artisan test` runs `shellcheck` over every script, then the bats suite. Both run in CI, which then migrates and queries SQLite and Postgres for real. ## Writing Tests Tests live in `tests/*.bats`: ```bash #!/usr/bin/env bats load test_helper @test "an unknown route is 404" { run http GET /nope [[ ${lines[0]} == $'HTTP/1.1 404 Not Found\r' ]] } ``` `run` captures the output in `$output` and `$lines`, and the exit code in `$status`. Any command that fails, fails the test. ### HTTP tests `http` sends a raw request to `bootstrap/handle` on stdin, exactly as socat would. No server is needed: ```bash http() { printf '%s %s HTTP/1.1\r\nHost: localhost\r\n\r\n' "$1" "$2" | "$BASE_PATH/bootstrap/handle" } ``` ### Isolation Each test gets its own SQLite database, queue folders and broadcast log in bats's temporary directory, so tests can run against a live application without touching it. ## Things We Learned - **bats waits for fd 3 to close.** A test that starts a background worker hangs forever, because the worker inherits fd 3. Start background processes with `3>&-`. - **Background jobs ignore SIGINT.** A non-interactive shell starts `&` jobs with `SIGINT` ignored, so `kill -INT` does nothing. Use `kill -TERM`. - **`! command` never fails a test.** `set -e` ignores commands that start with `!`. Use `run`, then check `$status`. ## ShellCheck ShellCheck finds the bugs you were going to write anyway: unquoted variables, `cd` without `|| exit`, `local x=$(cmd)` hiding exit codes. Every warning is fixed, or disabled on the line with a comment saying why. --- # Horizon Source: https://laravel-bash.mrstebo.co.uk/docs/horizon.md # Horizon ## Introduction Laravel Horizon provides a beautiful dashboard for your queues. Laravel Bash Horizon provides `pgrep`: ```bash ./sail artisan horizon ``` ```text Workers (pgrep -af queue:work) 13 bash ./artisan queue:work --workers=4 34 bash ./artisan queue:work --workers=4 35 bash ./artisan queue:work --workers=4 36 bash ./artisan queue:work --workers=4 37 bash ./artisan queue:work --workers=4 Jobs Pending ........................................................ 0 Processing ..................................................... 0 Failed ......................................................... 1 ``` The first process is the supervisor, and the other four are its workers. They show the same command line because each worker is a copy of the supervisor, made by `&`. The job counts are globs: `pending=("$QUEUE_PATH"/pending/*.job)`, then `${#pending[@]}`. With `nullglob` on, an empty folder is an empty array instead of one literal `*.job`. ## Watching ```bash ./sail shell watch -n 1 ./artisan horizon ``` For something with more colours, the [Queues](/queues) example follows the `queue` broadcast channel. --- # Pulse Source: https://laravel-bash.mrstebo.co.uk/docs/pulse.md # Pulse ## Introduction Laravel Pulse delivers at-a-glance insights into your application's performance and usage. Laravel Bash Pulse is a live feed of everything the application does: every request, job, event, listener and command, as it happens. Open [Pulse](/pulse) in one tab and use the app in another. ## How It Works Everything worth watching already broadcasts something: | What | Where it's broadcast from | |---|---| | Requests | `http::access_log`, when the response has been sent | | Jobs | `dispatch`, and each worker as it claims and finishes a job | | Events | `event`, and the listener after it handles one | | Commands | The Artisan example and the scheduler | The Pulse page follows the `pulse` channel. Every other channel's stream filters `broadcasts.log` with `grep --line-buffered "^channel"`. The `pulse` stream doesn't filter anything, and wraps each line with its channel name: ```text event: pulse data: {"channel":"queue","event":"JobProcessed","data":{"job":"ProcessPodcast 30","worker":"3","ms":"1051"}} ``` ## Storage There's no database for Pulse. `storage/broadcasts/broadcasts.log` is the database, and it grows forever. Delete it whenever you like: `tail -F` notices and carries on with the new one. --- # Sail Source: https://laravel-bash.mrstebo.co.uk/docs/sail.md # Laravel Sail ## Introduction Laravel Sail is a light-weight command-line interface for interacting with Laravel's default Docker development environment. Sail was always a Bash script, so Laravel Bash's Sail is the most authentic part of the project. ```bash ./sail up -d ./sail artisan migrate --seed ./sail test ./sail down ``` ## Why Docker? Laravel Bash needs Bash 5.1 for `wait -n -p` and GNU versions of `sed`, `sort`, `grep` and `tail`. macOS ships Bash 3.2 from 2007, licensed under GPLv2, and BSD tools whose flags differ: `sed -i` wants an argument on a Mac and doesn't on Linux. So `./sail` itself is careful to run on Bash 3.2, and everything else runs in a container. ### Why Debian, not Alpine? The obvious image is `bash:5` on Alpine, which is tiny. But Alpine's `sed`, `awk`, `grep` and `nc` come from BusyBox, which doesn't have `grep --line-buffered`, `sort -g`, `tail -F` or `column`. Laravel Bash uses `debian:bookworm-slim` and installs what it needs: ```bash apt-get install -y --no-install-recommends \ bash coreutils procps util-linux bsdextrautils socat sqlite3 \ postgresql-client jq curl ca-certificates bats shellcheck ``` ## Services | Service | Image | What it runs | |---|---|---| | `app` | `debian:bookworm-slim` | `./artisan dev`, on port 8000 | | `pgsql` | `postgres:17` | Postgres, with a health check so `app` waits for it | The project folder is mounted into `app`, so changes to any file apply on the next request, without a restart. Long-running processes (the queue workers, the listener and the scheduler) need `./sail restart app`. ## Commands | Command | Runs | |---|---| | `./sail up`, `down`, `ps`, `logs`, `restart` | `docker compose` | | `./sail artisan ...` | `./artisan` in the `app` container | | `./sail test` | `./artisan test` | | `./sail shell` | `bash` in the `app` container | | `./sail psql` | `psql` in the `pgsql` container | | `./sail sqlite` | `sqlite3` on the SQLite database | `./sail` passes `DB_CONNECTION` through when it's set on your machine, so `DB_CONNECTION=pgsql ./sail artisan migrate` does what it looks like. ---