Eloquent ORM (Object-Relational Mapping) is Laravel's built-in ActiveRecord implementation, providing a simple and expressive way to interact with your database. Eloquent allows you to work with database tables using PHP objects and provides an intuitive syntax for querying, inserting, updating, and deleting records.
Eloquent models serve as the bridge between your PHP code and database tables. Each Eloquent model represents a single database table, and each instance of the model corresponds to a row in that table.
To create an Eloquent model, you typically create a new PHP class that extends Laravel's Illuminate\Database\Eloquent\Model
class. Here's an example of a basic Eloquent model for a User
table:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// Model properties and methods
}
ActiveRecord
Eloquent makes it easy to define relationships between different database tables. You can define relationships like one-to-one, one-to-many, many-to-many, etc., using Eloquent's methods such as hasOne
, hasMany
, belongsTo
, belongsToMany
, etc.
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Eloquent provides expressive methods for performing CRUD (Create, Read, Update, Delete) operations on your database tables.
create()
method:$user = User::create(['name' => 'John Doe', 'email' => 'john@example.com']);
all()
, find()
, where()
, etc.$users = User::all();
$user = User::find(1);
$users = User::where('age', '>', 18)->get();
update()
method:$user = User::find(1);
$user->name = 'Jane Doe';
$user->save();
delete()
method:$user = User::find(1);
$user->delete();
Eloquent provides a fluent query builder interface that allows you to construct complex database queries using a readable syntax.
$users = User::where('age', '>', 18)
->orderBy('created_at', 'desc')
->get();