Databases in Leaf

Your database,
without the ceremony.

Leaf gives you three ways to work with your data. Db is a query builder for any PHP app. Eloquent models come with Leaf MVC. Schema files describe a table, its seeds and its fake data in one YAML file.

Try it
app.php

                
SQL
BINDINGS
users
id name email role

Toggle a chip, and the query, the generated SQL and the results stay in sync. Values always travel as bindings.

Db · leafs/db

A query builder for any PHP app.

Db gives MySQL, Postgres, SQLite and SQL Server one small API. It turns readable method chains into parameterised SQL.

  • ✓ where, filters and sorting as plain method calls
  • ✓ values always travel as bindings, never joined into the SQL
  • ✓ inserts check required and unique fields before they reach your table
  • ✓ works in Leaf, Laravel, Symfony, Slim or plain PHP

Read the database docs.

queries.php
$admins = db()
  ->select('users')
  ->where('role', 'admin')
  ->orderBy('created_at', 'desc')
  ->limit(10)
  ->all();

// or reach for the helpers
$user = db()->select('users')->find(1);
$vips = db()->select('users')
  ->where('plan', 'in', ['pro', 'team'])->all();

Db in practice

Safe writes

Values travel as bindings, and a unique check comes back as a plain error array.

signup.php
$saved = db()
  ->insert('users')
  ->params([
    'name' => $name,
    'email' => $email,
  ])
  ->unique('email')
  ->execute();

if (!$saved) {
  // ['email' => 'email already exists']
}

Relations

Load a record with its related rows in one call.

relations.php
// an author, with all their posts
$author = db()->select('users')
  ->where('id', 1)
  ->with('posts')
  ->first();

More than one database

Name your connections and switch per query with use().

connections.php
db()->connect([
  'main' => [/* mysql */],
  'analytics' => [/* postgres */],
], 'main');

Eloquent · Leaf MVC

An ORM for when your app grows.

Leaf MVC ships with Eloquent, the ORM from Laravel, and connects it from your .env. Each model is a class tied to one table.

  • ✓ relationships such as hasMany and belongsTo
  • ✓ casts and accessors
  • ✓ soft deletes and several connections
  • ✓ the query methods you know from Laravel

Read the models docs.

app/models/Flight.php
class Flight extends Model
{
    public function passengers()
    {
        return $this->hasMany(Passenger::class);
    }
}

// anywhere in your app
$flights = Flight::where('active', 1)
  ->orderBy('name', 'desc')
  ->take(10)
  ->get();

$flights[0]->passengers()->count();

Eloquent in practice

Relationships

Describe how models connect once, then follow the link from any record.

app/models/Passenger.php
public function flight()
{
    return $this->belongsTo(Flight::class);
}

// anywhere in your app
$passenger->flight->name;

Casts and accessors

Keep formatting rules on the model so every page gets the same value.

app/models/Flight.php
protected $casts = [
    'active' => 'boolean',
];

public function getNameAttribute($value)
{
    return ucfirst($value);
}

Soft deletes

Remove a row from view without losing it.

flights.php
$flight->delete();

// still there when you need it
Flight::withTrashed()->get();

Schema files · leafs/schema

One YAML file per table.

A schema file describes a table, its seeds and its fake data. Leaf MVC turns it into migrations and seeders for you.

  • ✓ columns and unique constraints in one place
  • ✓ seed rows with faker values such as @faker.name
  • ✓ ids and timestamps are added for you
  • ✓ run migrations and seeds with the leaf command

Read the schema files docs.

app/database/users.yml
# ids and timestamps are added for you
columns:
  name: string
  email:
    type: string
    unique: true
  age: integer

seeds:
  count: 10
  data:
    name: '@faker.name'
    email: '@faker.unique.safeEmail'
    age: '@faker.numberBetween(18, 65)'

Schema files in practice

1. Describe the table

List the columns. Ids and timestamps are added for you, and a column can be marked unique.

2. Generate it

Run one command and Leaf MVC turns the file into a migration and a seeder.

terminal
leaf g:schema users

3. Fill it with fake data

Faker rules in the same file give you realistic rows for development.

app/database/users.yml
seeds:
  count: 10
  data:
    name: '@faker.name'
    email: '@faker.unique.safeEmail'

Build in a weekend.
Query like you mean it.

Just the query builder, in any PHP app:

$ composer require leafs/db

A Leaf MVC app with everything above set up:

$ leaf create my-app --mvc

Then read the database docs.