Course › Week 6 · Laravel Go › Day 3 · lesson 38 of 42 · 45 min reading + 60 min practice
Models and migrations
Models as plain structs, a query builder with generics, relations and migrations in Go.
In the database lesson every query was SQL in a string, and every row was scanned into a struct by hand. Laravel Go has what Eloquent gives you: migrations, models, a query builder, relations, and eager loading. The models are still plain structs, and the queries are generic functions that return them.
Today the bookings of the routes lesson move into Postgres, with the properties they belong to. The API key middleware from that lesson is left out here to keep the requests short.
Migrations
1. A migration is a function
A migration is a Go function that takes a ctx and returns an error. schema.Create builds a table with a Blueprint, the same builder as Schema::create in PHP:
package migrations
import (
"context"
"go.laravel.com/schema"
)
func createPropertiesTable(ctx context.Context) error {
return schema.Create(ctx, "properties", func(table *schema.Blueprint) {
table.ID()
table.String("name")
table.String("city").Length(100)
table.Timestamps()
})
}
table.ID() is a bigserial primary key, table.String is a varchar(255) unless .Length says otherwise, and table.Timestamps() adds nullable created_at and updated_at. laravel make:migration create_properties_table writes this file for you, named with the current time in UTC, and adds it to the list in section 3.
There is no down: migrations only run forward, and there is no rollback command. To undo a change in a live app, write a new migration that drops the column. Each migration runs inside a transaction that its ctx carries, so on Postgres a failing one leaves nothing half-applied.
2. A foreign key, a default, an index
package migrations
import (
"context"
"go.laravel.com/schema"
)
func createBookingsTable(ctx context.Context) error {
return schema.Create(ctx, "bookings", func(table *schema.Blueprint) {
table.ID()
table.ForeignID("property_id").Constrained().RestrictOnDelete()
table.String("guest").Length(100)
table.String("email")
table.Date("check_in")
table.SmallInteger("nights")
table.String("status").Length(20).Default("pending")
table.Timestamps()
table.Index("property_id", "check_in")
})
}
ForeignID("property_id").Constrained() is a bigint with a foreign key to properties.id, the table taken from the column’s name, as in PHP. RestrictOnDelete refuses to delete a property that still has bookings. Default("pending") is a database default, and Index adds one index over two columns, for “a property’s bookings in date order”.
3. Listing the migrations
Nothing scans database/migrations/ (the Laravel Go lesson): a migration runs only when migrations.All lists it, under the name that is stored in the migrations table.
package migrations
import "go.laravel.com/db"
var All = []db.Migration{
{Name: "0001_01_01_000000_create_users_table", Run: createUsersTable},
{Name: "0001_01_01_000001_create_cache_table", Run: createCacheTable},
{Name: "0001_01_01_000002_create_jobs_table", Run: createJobsTable},
{Name: "2026_12_04_090000_create_properties_table", Run: createPropertiesTable},
{Name: "2026_12_04_090100_create_bookings_table", Run: createBookingsTable},
}
Migrating `0001_01_01_000000_create_users_table`...
Migrating `0001_01_01_000001_create_cache_table`...
Migrating `0001_01_01_000002_create_jobs_table`...
Migrating `2026_12_04_090000_create_properties_table`...
Migrating `2026_12_04_090100_create_bookings_table`...
5 migrations ran.Migration Batch Status
0001_01_01_000000_create_users_table 1 ran
0001_01_01_000001_create_cache_table 1 ran
0001_01_01_000002_create_jobs_table 1 ran
2026_12_04_090000_create_properties_table 1 ran
2026_12_04_090100_create_bookings_table 1 ranmigrate ran the starter’s three migrations and the two new ones, all in batch 1. Run it again and it says there is nothing to do, because each name is now in the migrations table. migrate:fresh drops every table and runs them all again, for your machine only.
Models
4. A model is a struct
A model is a struct with an ID field and a field per column. The table is the struct’s name in snake case and plural (Booking is bookings), and a column is the field’s name in snake case (PropertyID is property_id, CheckIn is check_in):
package models
import (
"time"
"go.laravel.com/date"
)
type Status string
const (
Pending Status = "pending"
Confirmed Status = "confirmed"
)
type Booking struct {
ID int64 `json:"id"`
PropertyID int64 `json:"property_id"`
Guest string `json:"guest"`
Email string `json:"email"`
CheckIn date.Date `json:"check_in"`
Nights int `json:"nights"`
Status Status `json:"status" db:",default"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Status is a named type with constants, like Level in the structs lesson, but built on string instead of iota, so the column holds readable text: the Go form of a backed PHP enum. db:",default" matters because Go cannot tell “not set” from "": with the tag, a Booking created with an empty Status leaves the column out of the INSERT, so the database default pending applies, and the stored value is read back into the struct.
CreatedAt and UpdatedAt are filled on create and UpdatedAt on every update, like Eloquent’s timestamps. A nullable column would be a pointer, such as *string. models/property.go is the same shape, with Name and City.
5. A seeder
A seeder is a named function in database/seeders/seeders.go; db:seed runs the list in order:
package seeders
import (
"context"
"time"
laravel "go.laravel.com"
"go.laravel.com/date"
"go.laravel.com/model"
"app/models"
)
var All = []laravel.Seeder{
{Name: "bookings", Run: bookings},
}
func bookings(ctx context.Context) error {
cabin := models.Property{Name: "Fjord Cabin", City: "Bergen"}
if err := model.Create(ctx, &cabin); err != nil {
return err
}
loft := models.Property{Name: "Harbour Loft", City: "Oslo"}
if err := model.Create(ctx, &loft); err != nil {
return err
}
for _, b := range []models.Booking{
{PropertyID: cabin.ID, Guest: "Lina", Email: "lina@example.com", CheckIn: date.Date{Year: 2027, Month: time.January, Day: 14}, Nights: 3, Status: models.Confirmed},
{PropertyID: cabin.ID, Guest: "Omar", Email: "omar@example.com", CheckIn: date.Date{Year: 2027, Month: time.February, Day: 2}, Nights: 7},
{PropertyID: loft.ID, Guest: "Sara", Email: "sara@example.com", CheckIn: date.Date{Year: 2027, Month: time.January, Day: 20}, Nights: 2},
} {
if err := model.Create(ctx, &b); err != nil {
return err
}
}
return nil
}
bookings 6.3ms
Database seeded.model.Create(ctx, &cabin) inserts the row and fills the struct with its new ID, its timestamps and its defaults, so cabin.ID is ready for the bookings. It takes a pointer because it writes into your struct. The whole seeding run is one transaction carried by ctx: if the third booking failed, no property and no booking would be left behind.
Queries
6. model.Query
model.Query[models.Booking]() starts a query builder for the bookings table that returns []models.Booking. The strict status filter of the routes lesson stays, now with the Status constants:
package bookings
import (
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type Filters struct {
Status models.Status `json:"status"`
}
func Index(r *web.Request) *web.Response {
filters, err := r.Query[Filters]()
if err != nil {
return web.Fail(err)
}
failed, err := validation.Validate(r, &filters,
rule.Field(&filters.Status, rule.In(models.Pending, models.Confirmed)),
)
if err != nil {
return web.Fail(err)
}
if len(failed) > 0 {
return web.InvalidErrors(failed)
}
query := model.Query[models.Booking]().OrderBy("check_in")
if filters.Status != "" {
query = query.WhereEq("status", filters.Status)
}
bookings, err := query.Get(r)
if err != nil {
return web.Fail(err)
}
return web.JSON(map[string][]models.Booking{"data": bookings})
}
HTTP/1.1 200 OK
Content-Length: 422
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 166f5e048df7db78aa080b5f59e54a9a
{"data":[{"id":3,"property_id":2,"guest":"Sara","email":"sara@example.com","check_in":"2027-01-20","nights":2,"status":"pending","created_at":"2026-12-03T19:26:18.861794Z","updated_at":"2026-12-03T19:26:18.861794Z"},{"id":2,"property_id":1,"guest":"Omar","email":"omar@example.com","check_in":"2027-02-02","nights":7,"status":"pending","created_at":"2026-12-03T19:26:18.86122Z","updated_at":"2026-12-03T19:26:18.86122Z"}]}Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
GET 200 /api/bookings 9.7ms
Stopping. Waiting up to 20s for the work in progress.The two pending bookings, in check_in order. A query builder is an immutable value: query.WhereEq(…) returns a new builder and leaves query as it was, which is why the result is assigned back. Nothing runs until Get(r), which takes the request as its context, so the query stops when the request is cancelled (the context lesson).
Column names are checked against the model when the query is built: a typo like "chek_in" panics at once, with the list of real columns. So never pass a column name from the request (a ?sort= value) to a query without checking it against an allow-list.
7. A model from the route
model.FromRoute reads the {booking} parameter, parses it as the type of the model’s ID, and loads the row:
package bookings
import (
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type Filters struct {
Status models.Status `json:"status"`
}
func Index(r *web.Request) *web.Response {
filters, err := r.Query[Filters]()
if err != nil {
return web.Fail(err)
}
failed, err := validation.Validate(r, &filters,
rule.Field(&filters.Status, rule.In(models.Pending, models.Confirmed)),
)
if err != nil {
return web.Fail(err)
}
if len(failed) > 0 {
return web.InvalidErrors(failed)
}
query := model.Query[models.Booking]().OrderBy("check_in")
if filters.Status != "" {
query = query.WhereEq("status", filters.Status)
}
bookings, err := query.Get(r)
if err != nil {
return web.Fail(err)
}
return web.JSON(map[string][]models.Booking{"data": bookings})
}
func Show(r *web.Request) *web.Response {
booking, err := model.FromRoute[models.Booking](r, "booking")
if err != nil {
return web.Fail(err)
}
return web.JSON(map[string]models.Booking{"data": booking})
}
HTTP/1.1 200 OK
Content-Length: 215
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 06e4a952434d696a6811e18cb9a82bda
{"data":{"id":2,"property_id":1,"guest":"Omar","email":"omar@example.com","check_in":"2027-02-02","nights":7,"status":"pending","created_at":"2026-12-03T19:26:29.161171Z","updated_at":"2026-12-03T19:26:29.161171Z"}}HTTP/1.1 404 Not Found
Content-Length: 54
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: a464179b3fd13a6dfbe059b0d0727a43
{"message":"db: no row in bookings matched the query"}HTTP/1.1 404 Not Found
Content-Length: 54
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: d242c7aa7054a0cbbbb2613740d01cb1
{"message":"db: no row in bookings matched the query"}Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
GET 200 /api/bookings/2 8.4ms
GET 404 /api/bookings/99 0.8ms
GET 404 /api/bookings/abc 0.1ms
Stopping. Waiting up to 20s for the work in progress.It is route model binding: a missing row and a parameter that is not a number are both a 404. The message is the database error, shown because APP_DEBUG=true; with APP_DEBUG=false the body is {"message":"Not Found"}.
8. Creating a model, and an Exists rule
Store validates, copies the allowed fields into a models.Booking, and creates it:
package bookings
import (
"go.laravel.com/date"
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type Filters struct {
Status models.Status `json:"status"`
}
func Index(r *web.Request) *web.Response {
filters, err := r.Query[Filters]()
if err != nil {
return web.Fail(err)
}
failed, err := validation.Validate(r, &filters,
rule.Field(&filters.Status, rule.In(models.Pending, models.Confirmed)),
)
if err != nil {
return web.Fail(err)
}
if len(failed) > 0 {
return web.InvalidErrors(failed)
}
query := model.Query[models.Booking]().OrderBy("check_in")
if filters.Status != "" {
query = query.WhereEq("status", filters.Status)
}
bookings, err := query.Get(r)
if err != nil {
return web.Fail(err)
}
return web.JSON(map[string][]models.Booking{"data": bookings})
}
func Show(r *web.Request) *web.Response {
booking, err := model.FromRoute[models.Booking](r, "booking")
if err != nil {
return web.Fail(err)
}
return web.JSON(map[string]models.Booking{"data": booking})
}
type StoreBooking struct {
PropertyID int64 `json:"property_id"`
Guest string `json:"guest"`
Email string `json:"email" transform:"lowercase"`
CheckIn date.Date `json:"check_in"`
Nights int `json:"nights"`
}
func (f *StoreBooking) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.PropertyID, rule.Required, model.Exists[models.Property]()),
rule.Field(&f.Guest, rule.Required, rule.Max(100)),
rule.Field(&f.Email, rule.Required, rule.Email),
rule.Field(&f.CheckIn, rule.Required),
rule.Field(&f.Nights, rule.Required, rule.Min(1), rule.Max(30)),
)
}
func Store(r *web.Request) *web.Response {
form, err := r.Validate[StoreBooking]()
if err != nil {
return web.Fail(err)
}
booking := models.Booking{
PropertyID: form.PropertyID,
Guest: form.Guest,
Email: form.Email,
CheckIn: form.CheckIn,
Nights: form.Nights,
}
if err := model.Create(r, &booking); err != nil {
return web.Fail(err)
}
return web.Created(map[string]models.Booking{"data": booking})
}
HTTP/1.1 201 Created
Content-Length: 213
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: e7ef2e13ec7f411d3ff217ca65008b9a
{"data":{"id":4,"property_id":2,"guest":"Ali","email":"ali@example.com","check_in":"2027-03-01","nights":2,"status":"pending","created_at":"2026-12-03T19:26:39.812063Z","updated_at":"2026-12-03T19:26:39.812063Z"}}HTTP/1.1 422 Unprocessable Entity
Content-Length: 116
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 57d808cbbd1916054e386f56b96f2600
{"message":"The selected property id is invalid.","errors":{"property_id":["The selected property id is invalid."]}}Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST 201 /api/bookings 12.5ms
POST 422 /api/bookings 2.4ms
Stopping. Waiting up to 20s for the work in progress.The 201 has what the database gave the row: id 4, status from the column’s default, and the timestamps. model.Exists[models.Property]() is exists:properties,id: it runs a query, so a property that does not exist is a 422 on its field, not a foreign-key error from Postgres.
The rule is not a lock. A property deleted between the check and the insert still makes the insert fail, and that 500 is correct: the foreign key is the real guarantee, the rule is the readable message.
Relations
9. belongs_to, loaded with With
A relation is a field with a model tag. A booking belongs to a property, so Booking gets a *Property field tagged model:"belongs_to"; the foreign key is the relation’s name plus _id, property_id:
package models
import (
"time"
"go.laravel.com/date"
)
type Status string
const (
Pending Status = "pending"
Confirmed Status = "confirmed"
)
type Booking struct {
ID int64 `json:"id"`
PropertyID int64 `json:"property_id"`
Guest string `json:"guest"`
Email string `json:"email"`
CheckIn date.Date `json:"check_in"`
Nights int `json:"nights"`
Status Status `json:"status" db:",default"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Property *Property `json:"property,omitzero" model:"belongs_to"`
}
Show now asks for it: model.Query[models.Booking]().With("property").FromRoute(r, "booking"), the Booking::with('property') of Eloquent.
10. The queries it runs
LOG_LEVEL=debug logs every query with its SQL (not its values) and the request’s id:
package bookings
import (
"go.laravel.com/date"
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type Filters struct {
Status models.Status `json:"status"`
}
func Index(r *web.Request) *web.Response {
filters, err := r.Query[Filters]()
if err != nil {
return web.Fail(err)
}
failed, err := validation.Validate(r, &filters,
rule.Field(&filters.Status, rule.In(models.Pending, models.Confirmed)),
)
if err != nil {
return web.Fail(err)
}
if len(failed) > 0 {
return web.InvalidErrors(failed)
}
query := model.Query[models.Booking]().OrderBy("check_in")
if filters.Status != "" {
query = query.WhereEq("status", filters.Status)
}
bookings, err := query.Get(r)
if err != nil {
return web.Fail(err)
}
return web.JSON(map[string][]models.Booking{"data": bookings})
}
func Show(r *web.Request) *web.Response {
booking, err := model.Query[models.Booking]().With("property").FromRoute(r, "booking")
if err != nil {
return web.Fail(err)
}
return web.JSON(map[string]models.Booking{"data": booking})
}
type StoreBooking struct {
PropertyID int64 `json:"property_id"`
Guest string `json:"guest"`
Email string `json:"email" transform:"lowercase"`
CheckIn date.Date `json:"check_in"`
Nights int `json:"nights"`
}
func (f *StoreBooking) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.PropertyID, rule.Required, model.Exists[models.Property]()),
rule.Field(&f.Guest, rule.Required, rule.Max(100)),
rule.Field(&f.Email, rule.Required, rule.Email),
rule.Field(&f.CheckIn, rule.Required),
rule.Field(&f.Nights, rule.Required, rule.Min(1), rule.Max(30)),
)
}
func Store(r *web.Request) *web.Response {
form, err := r.Validate[StoreBooking]()
if err != nil {
return web.Fail(err)
}
booking := models.Booking{
PropertyID: form.PropertyID,
Guest: form.Guest,
Email: form.Email,
CheckIn: form.CheckIn,
Nights: form.Nights,
}
if err := model.Create(r, &booking); err != nil {
return web.Fail(err)
}
return web.Created(map[string]models.Booking{"data": booking})
}
HTTP/1.1 200 OK
Content-Length: 358
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 9562bfe11e613fb25ec77cb993ef84c1
{"data":{"id":2,"property_id":1,"guest":"Omar","email":"omar@example.com","check_in":"2027-02-02","nights":7,"status":"pending","created_at":"2026-12-03T19:26:52.454092Z","updated_at":"2026-12-03T19:26:52.454092Z","property":{"id":1,"name":"Fjord Cabin","city":"Bergen","created_at":"2026-12-03T19:26:52.450952Z","updated_at":"2026-12-03T19:26:52.450952Z"}}}Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
time=2026-12-03T21:26:52.674+02:00 level=DEBUG msg=query sql="select \"bookings\".* from \"bookings\" where \"bookings\".\"id\" = $1 limit 1" duration_ms=6.819 dialect=postgres request_id=9562bfe11e613fb25ec77cb993ef84c1
time=2026-12-03T21:26:52.675+02:00 level=DEBUG msg=query sql="select \"properties\".*, \"properties\".\"id\" as \"laravel_parent\" from \"properties\" where \"properties\".\"id\" in ($1)" duration_ms=0.514 dialect=postgres request_id=9562bfe11e613fb25ec77cb993ef84c1
GET 200 /api/bookings/2 8.0ms
Stopping. Waiting up to 20s for the work in progress.
time=2026-12-03T21:26:52.677+02:00 level=DEBUG msg="command finished" exit_code=0 duration_ms=208.776Two queries: the booking, then its property with where id in (…). For a list of 50 bookings it is still two queries, never 51, because With loads the relation for all the rows at once.
There is no lazy loading. Eloquent would run a query the first time you read $booking->property; in Go a field is just a field. Without With, Property stays nil: omitzero leaves it out of the JSON, and booking.Property.Name in Go code panics with a nil pointer. A has_many slice that was not loaded is empty, so a forgotten With("bookings") shows “no bookings” instead of failing. Load what you read, and test it.
Coming from PHP
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Booking extends Model
{
protected $fillable = ['property_id', 'guest', 'email', 'check_in', 'nights'];
protected $casts = ['check_in' => 'date', 'status' => BookingStatus::class];
public function property(): BelongsTo
{
return $this->belongsTo(Property::class);
}
}
An Eloquent model is an active record: it knows its table, saves itself, and loads a relation when you first touch it. Its columns are not declared anywhere in the class; $booking->gest is null, not an error. A Laravel Go model is the opposite: a struct whose fields are the columns, with types the compiler checks, and functions in the model package that read and write it. There is no $fillable because the form struct (the routes lesson) is the list, and no $casts because the field’s type is the cast.
What you give up is the magic: no lazy loading, no accessors on the model, no $booking->save(). What you get is that every query a handler runs is visible in its code.
PracticeThe models and relationships guides; a property’s bookings
Read models.md (retrieving, creating and updating models) and the “Declaring relationships” and “Eager loading” parts of model-relationships.md, in the app’s bundled docs.
Exercise: GET /api/properties/{property}
Add Bookings []Booking with model:"has_many" to Property, and a properties.Show that returns the property with its bookings in date order: model.Query[models.Property]().With("bookings").FromRoute(r, "property"), then find in the docs how to order an eager load. Run it with LOG_LEVEL=debug and count the queries. Then remove With and look at the JSON: what tells a client that the bookings were not loaded, and what does not?
Remember
- Migrations are Go functions listed in
migrations.All; they only run forward, so a change is a new migration. - Tag a column with a database default
db:",default", or Go’s zero value overwrites it. - There is no lazy loading:
Withwhat you read, or the field is nil. - Never pass a column name from the request to a query: an unknown column panics.
Tomorrow: queued jobs with retries, and several queries at once with the task package.