laravel-eloquent-orm-en-laravel

Eloquent ORM in Laravel

  • 3 min

Eloquent is Laravel’s ORM that relates PHP models to database records.

In Module 7 you learned to write SELECT * FROM usuarios WHERE id = 1 and use PDO. That was fine for learning, but writing SQL by hand is slow, error-prone, and tedious.

Eloquent is Laravel’s ORM (Object-Relational Mapper). It allows you to query and modify records through PHP models.

The logic: model = table

The rule is super simple: Each table in your database has an associated “Model” (Class).

  • If you have the table productos (plural), you’ll have the model Producto (singular).
  • If you have the table users (plural), you’ll have the model User (singular).

To create a model, we use our friend Artisan:

php artisan make:model Producto
Copied!

This creates app/Models/Producto.php. Eloquent applies conventions to relate Producto to the table productos and exposes retrieved attributes as dynamic properties. It does not inspect the table to declare PHP properties; casts, mass assignment, and other rules are configured in the model.

Forget SQL: CRUD with Eloquent

Let’s see how to do the 4 basic operations. Notice that there isn’t a single line of SQL code. Everything is pure, object-oriented PHP.

Suppose we are inside a Controller:

A. Read

use App\Models\Producto;

// 1. Get ALL products (SELECT * FROM Productos)
$todos = Producto::all();

foreach ($todos as $item) {
    echo $item->nombre; // Access the 'nombre' column as if it were a property
}

// 2. Find by ID (SELECT * FROM productos WHERE id = 5)
$producto = Producto::find(5); // Returns null if it doesn't exist

// 3. Complex queries (SELECT * FROM productos WHERE precio > 100 AND activo = 1)
// Notice how readable it is ("get" executes the query)
$caros = Producto::where('precio', '>', 100)
                 ->where('activo', true)
                 ->get();
Copied!

B. Create

Forget INSERT INTO.... Simply create a new object, fill in its data, and save it.

$nuevo = new Producto();

// Assign values to the columns
$nuevo->nombre = "Monitor 4K";
$nuevo->precio = 299.99;
$nuevo->descripcion = "High-resolution screen";

// Save to DB. Eloquent performs the INSERT and automatically protects against SQL injection.
$nuevo->save(); 
Copied!

C. Update

First, find the record you want to edit, change the value, and save again.

// 1. Find product 5 or throw a 404 exception
$producto = Producto::findOrFail(5);

// 2. Change only what we want
$producto->precio = 150.00;

// 3. Save the changes (Laravel does the UPDATE automatically)
$producto->save();
Copied!

D. Delete

$producto = Producto::findOrFail(5);
$producto->delete(); // Goodbye record
Copied!

The real power: relationships

The hardest part in pure SQL is the JOIN (joining tables). “Get me the orders of the user who bought X…”. Eloquent makes relationships read like plain English.

If you configure your models correctly (saying “A User has many Orders”), you can do this:

$usuario = User::find(1);

// Laravel queries the 'pedidos' relationship when accessing the property
// and returns the orders for THIS user.
foreach ($usuario->pedidos as $pedido) {
    echo $pedido->fecha;
}
Copied!