MANUAL

Writing SQL queries and migrations

Writing SQL queries and migrations

Almost every app stores data in a relational database such as MySQL, MariaDB, PostgreSQL or SQLite. You interact with it using SQL. In Laravel, you usually write Eloquent code, but this is converted to SQL behind the scenes. If you understand SQL, you’ll also understand why something is slow or incorrect.

01

The basics

SELECT id, naam, email
FROM klanten
WHERE plaats = 'Groningen'
ORDER BY naam
LIMIT 20;

02

Combining tables using JOIN

SELECT k.naam, f.nummer, f.bedrag
FROM facturen f
INNER JOIN klanten k ON k.id = f.klant_id
WHERE f.betaald = 0;
JOIN Displays
INNER JOIN Only rows that match in both tables
LEFT JOIN All rows on the left, even if there is no match (the right-hand side becomes NULL)
RIGHT JOIN The other way round
FULL OUTER JOIN Everything from both sides (not in MySQL)

03

Counting and grouping

SELECT klant_id, COUNT(*) AS aantal, SUM(bedrag) AS totaal
FROM facturen
GROUP BY klant_id
HAVING SUM(bedrag) > 1000;

WHERE filters rows before grouping, HAVING filters the groups afterwards.

04

Indexes: why a query is slow

An index works like the index at the back of a book. Without an index, the database reads the entire table. Create an index on columns that you frequently search, filter or join by (klant_id, email, created_at).

See how the database executes a query:

EXPLAIN SELECT * FROM facturen WHERE klant_id = 42;

Do you see the word type``ALL in MySQL? If so, the entire table is being read and there is probably no index.

05

Migrations in Laravel

A migration is a file that describes how your database changes. This ensures that everyone (and the live server) has exactly the same structure.

php artisan make:migration create_facturen_table
Schema::create('facturen', function (Blueprint $table) {
    $table->id();
    $table->foreignId('klant_id')->constrained()->cascadeOnDelete();
    $table->string('nummer')->unique();
    $table->decimal('bedrag', 10, 2);
    $table->boolean('betaald')->default(false)->index();
    $table->timestamps();
});
php artisan migrate            # uitvoeren
php artisan migrate:rollback   # laatste stap terugdraaien

Rules:

06

The N+1 problem

This code looks harmless:

foreach (Factuur::all() as $factuur) {
    echo $factuur->klant->naam;   // elke keer een extra query
}

With 500 invoices, that amounts to 501 queries. The solution is eager loading:

foreach (Factuur::with('klant')->get() as $factuur) {
    echo $factuur->klant->naam;   // 2 queries in totaal
}

Tip: Add AppServiceProvider Model::preventLazyLoading(! app()->isProduction()); to your AppServiceProvider. This will trigger a local error message as soon as this happens.

07

Security: SQL injection

Never hard-code user input into an SQL string. Use Eloquent or placeholders:

DB::select('SELECT * FROM klanten WHERE email = ?', [$email]);   // goed
DB::select("SELECT * FROM klanten WHERE email = '$email'");      // FOUT

08

Need help?

Has your app become slow, or are you unsure whether your queries are secure? I’ll take a look at it as part of AI code review. Setting up a new database falls under Bespoke software and web applications.

09

Skills

10

Related services