4.2Laravel: routes, Blade, Eloquent (ORM), migrations
The essentials in 30 seconds
- Routing + controllers:
Route::get('/produits', [ProduitController::class, 'index'])directs the URL to the action; Artisan generates the code. - Blade + Eloquent:
{{ }}templates with auto-escaping (anti-XSS), and the database handled as objects (Produit::where(...)->get()) with automatic prepared statements. - Riad's reflex: version the database in migrations and understand the generated SQL (beware the N+1) instead of suffering the ORM.
Running case — Riad moves his catalogue to Laravel
Riad's MVC catalogue (4.1) is growing: he ports it to Laravel in Constantine. He declares his routes to a ProduitController, renders with a Blade view that escapes by default, reads the database via Eloquent without writing SQL, and describes the products table in a migration versioned with Git. When a colleague picks up the project, one command installs, another migrates — and the database is identical. Second milestone of the thread: productive, structured and safe by default.
Continues the 4.1 case — Riad industrializes his MVC with a framework.
1. Routing, controllers, Artisan
Laravel implements MVC with elegant tooling. Routing maps URLs to actions: Route::get('/produits', [ProduitController::class, 'index']) sends GET requests to the index method — expressive (GET/POST, parameters, groups, middlewares). Controllers handle requests (receive, call models, return a view or response). The Artisan command line generates controllers and models, runs migrations: Riad scaffolds in seconds instead of copy-pasting.
2. Blade: safe views
Blade is the template engine: {{ $variable }} to display, @foreach and @if for display logic, reusable layouts through inheritance. Its major asset: automatic escaping — data is escaped by default, which protects against XSS without thinking about it. Riad replaces his raw PHP/HTML mix with readable, safe templates.
3. Eloquent and migrations: the data
Eloquent is the ORM: tables become classes, rows become objects — Produit::all(), Produit::find($id), Produit::where('prix', '>', 100)->get(), $produit->save() — with automatic prepared statements (anti-injection) and elegant relations. Migrations version the database structure as PHP code: reproducible, traceable, essential in teams and on deployment. Riad keeps two warnings in mind: understand the generated SQL and avoid the N+1 through eager loading (with()). Laravel adds auth, validation, automatic CSRF, secure sessions: an excellent investment, the most in-demand framework.
🔎 Concrete example — 🔎 Concrete example — Product catalogue in Laravel
Riad's four moves, with the real APIs:
Route::get('/produits', [ProduitController::class, 'index']);
$produits = Produit::where('prix', '>', 100)->get(); // all(), find($id)
return view('produits.index', ['produits' => $produits]);
Blade: {{ $p->nom }} + @foreach ($produits as $p) ... @endforeach
Reading: route, object query, view, template — each in its place.
Lesson: the framework enforces MVC and security by default.
Section vocabulary
- Laravel
- The most popular PHP framework (elegant, productive, vast ecosystem); implements MVC with best practices. The reference of modern PHP.
Simple example: Riad ports his catalogue there to move fast without sacrificing structure.
What it is not: a pile of scripts with no routing or ORM.
Reflex: think routes, controllers, Blade, Eloquent, migrations.
- Routing / controllers / Artisan
- Routing: URLs → actions (Route::get). Controllers: handle requests. Artisan: CLI that generates code and runs migrations.
Simple example: Riad's /produits route points to ProduitController@index, generated by Artisan.
What it is not: a hand-crafted PHP file per URL.
Reflex: one URL = one named route to a clear action.
- Blade (templates)
- Laravel template engine: {{ }}, @foreach, @if, layouts — with AUTOMATIC ESCAPING (anti-XSS by default).
Simple example: Riad renders {{ $p->nom }} without fearing HTML injection.
What it is not: PHP echoes tangled with HTML and no escaping.
Reflex: {{ }} by default; {!! !!} only when you know what you are doing.
- Eloquent (ORM)
- Laravel ORM: tables ↔ classes, rows ↔ objects; database handled as objects/methods, automatic prepared statements, elegant relations.
Simple example: Riad reads Produit::where('prix', '>', 100)->get() instead of writing the SELECT.
What it is not: SQL concatenated with unescaped variables.
Reflex: check the generated SQL and hunt the N+1 with with().
- Migrations
- Database structure versioned as PHP code (with Git): reproducible, traceable — essential in teams and on deployment.
Simple example: Riad's products table is born from a migration, replayed identically everywhere.
What it is not: ALTER TABLE statements done by hand in production.
Reflex: never change the structure outside a migration.
In practice — In practice — Build with Laravel
- Create a Laravel project (via Composer), explore routes, controllers, models, Blade views and the Artisan CLI.
- Define routes (Route::get/post) to controllers; create a Blade view with {{ }} and @foreach (automatic escaping).
- Use Eloquent: model + CRUD as objects (all/find/where/save) with no SQL, automatic prepared statements.
- Create a migration to version a table; enable the provided auth, validation and CSRF protection.
Ready-to-say script — argue for moving to Laravel (30 s)
"This is Riad: with Laravel, our routes are explicit, our Blade views escape by default, Eloquent prepares our queries and our migrations version the database. We ship faster, with security built in instead of cobbled together."
Say it in a technical meeting; show route + Blade + migration.
Copy-paste template — Laravel CRUD (tested code)
', 100)->get();
return view('produits.index', ['produits' => $produits]);
}
public function store(Request $request) {
$valide = $request->validate(['nom' => 'required|string|max:255', 'prix' => 'required|numeric|min:0']);
$produit = Produit::create($valide);
return response()->json($produit, 201);
}
}
// resources/views/produits/index.blade.php
// @foreach ($produits as $p) {{ $p->nom }} — {{ $p->prix }} DA @endforeach
// database/migrations/xxxx_create_produits_table.php (excerpt)
// Schema::create('produits', function (Blueprint $t) {
// $t->id(); $t->string('nom'); $t->decimal('prix', 10, 2); $t->timestamps();
// });
Small showcase site
Routes + Blade are enough: keep Eloquent for what deserves a database, without over-modelling.
Real application
Like Riad: named routes, resource controllers, Eloquent with eager loading, everything in migrations.
Slow list (N+1)
Load relations in one go (with('categorie')): one query instead of one per row.
Beginner team
Forbid concatenated SQL and unescaped HTML: the framework already does both.
validate()), let Blade escape by default and keep secrets in .env, never hardcoded. Teaching content, examples with fictitious data.✓ Best practices
- Respect the MVC imposed by the framework.
- Understand the SQL generated by Eloquent.
- Version the database in migrations.
✗ Common pitfalls
- Putting logic in Blade templates.
- Ignoring the N+1 (black-box ORM).
- Recoding the already-provided auth/validation/CSRF.
Key takeaways
- LARAVEL = most POPULAR PHP framework: MVC, productivity, built-in security. The reference.
- ROUTING (Route::get → actions), CONTROLLERS, ARTISAN (generate, migrate).
- BLADE: {{ }}, @foreach, AUTO-ESCAPING (anti-XSS). ELOQUENT: objects instead of SQL, automatic prepared statements, relations.
- MIGRATIONS: versioned database = reproducible and traceable. Plus automatic auth, validation, CSRF.
48h challenge — apply it tomorrow
Ship 1 CRUD resource with Laravel: 2 routes + 1 Blade view + Eloquent + 1 migration, without a single line of hand-written SQL.
- I can name routes, Blade, Eloquent, migrations.
- I can explain auto-escaping and automatic prepared statements.
- I have 1 running Laravel CRUD.
Frequently asked questions
What does a framework like Laravel bring compared to hand-written PHP?
Imposed MVC structure (no more spaghetti), productivity (ORM, templates, routing, Artisan, dozens of ready-made features), security integrated by default (Blade escaping anti-XSS, Eloquent prepared statements anti-injection, automatic CSRF, hashing, robust auth) and battle-tested features (auth, validation, sessions, e-mails, files, tests, migrations). You build complete applications much faster, with fewer errors — hence its status as a pro must-have.
What is an ORM like Eloquent — and do you still need to know SQL?
An ORM maps objects ↔ tables (tables ↔ classes, rows ↔ objects, columns ↔ properties): Produit::all() instead of SELECT *. Benefits: productivity, security (automatic prepared statements), readability, elegant relations ($utilisateur->commandes). But YES, SQL remains essential: to understand and optimize what the ORM generates (N+1, indexes, joins) and for complex queries. Eloquent + SQL basics = the right duo.
What does Eloquent bring compared to hand-written SQL?