Managing Databases in Laravel with Eloquent ORM
This article explains how to use Eloquent ORM in Laravel to manage databases, including creating models, relationships, queries and best practices.
Summary
- What is Eloquent ORM?
- Creating models
- Migrations and database structure
- Relationships between models
- Eloquent queries
- Best practices
- Conclusion
What is Eloquent ORM?
Eloquent ORM is Laravel's native Object-Relational Mapper, which lets you interact with the database through PHP models, without writing raw SQL.
Creating models
php artisan make:model Post -m
This creates the Post model and a matching migration.
Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'content'];
}
Migrations and database structure
Example migration:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
Run the migrations:
php artisan migrate
Relationships between models
- One-to-Many:
class User extends Model { public function posts() { return $this->hasMany(Post::class); } } - Many-to-Many:
class Role extends Model { public function users() { return $this->belongsToMany(User::class); } }
Eloquent queries
// All posts
$posts = Post::all();
// Post by id
$post = Post::find(1);
// Create a post
Post::create(['title' => 'Title', 'content' => 'Content']);
// Update
$post->update(['title' => 'New title']);
// Delete
$post->delete();
Best practices
- Use
$fillableor$guardedfor protection. - Use relationships to avoid repeated queries.
- Take advantage of scopes for reusable filters.
Conclusion
Eloquent ORM makes managing databases in Laravel more intuitive and faster, letting developers write clean, structured code.