Models and Eloquent ORM

πŸ“˜ Laravel πŸ‘ 50 views πŸ“… Dec 22, 2025
⏱ Estimated reading time: 2 min

Models in Laravel represent the data layer of an application. They interact with the database and contain the business logic related to data. Laravel uses Eloquent ORM (Object–Relational Mapping), which allows developers to work with database records as PHP objects in a simple and expressive way.


1. What Is a Model?

A model represents a database table and is responsible for:

  • Retrieving data

  • Inserting new records

  • Updating existing records

  • Deleting records

Models are stored in:

app/Models

Example:
A User model typically represents the users table.


2. Creating a Model

Laravel provides an Artisan command to create models:

php artisan make:model Post

This creates:

app/Models/Post.php

To create a model with a migration:

php artisan make:model Post -m

3. Basic Model Structure

Example model:

<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $table = 'posts'; }

By convention:

  • Model name β†’ Singular (Post)

  • Table name β†’ Plural (posts)


4. Mass Assignment

To protect against unwanted data insertion, Laravel uses mass assignment rules.

protected $fillable = ['title', 'content'];

Or:

protected $guarded = ['id'];

5. Retrieving Data with Eloquent

Get All Records

$posts = Post::all();

Find by ID

$post = Post::find(1);

Conditional Queries

$posts = Post::where('status', 'published')->get();

6. Inserting Data

$post = new Post(); $post->title = 'Laravel ORM'; $post->content = 'Eloquent makes databases easy.'; $post->save();

Or using mass assignment:

Post::create([ 'title' => 'Laravel', 'content' => 'Eloquent ORM example' ]);

7. Updating Data

$post = Post::find(1); $post->title = 'Updated Title'; $post->save();

Or:

Post::where('id', 1)->update(['title' => 'Updated']);

8. Deleting Data

Post::find(1)->delete();

9. Eloquent Relationships

Eloquent makes database relationships easy.

One-to-One

public function profile() { return $this->hasOne(Profile::class); }

One-to-Many

public function comments() { return $this->hasMany(Comment::class); }

Many-to-Many

public function roles() { return $this->belongsToMany(Role::class); }

10. Eloquent Query Builder

Chained queries:

$posts = Post::where('status', 'published') ->orderBy('created_at', 'desc') ->limit(5) ->get();

11. Timestamps

By default, Eloquent manages timestamps:

  • created_at

  • updated_at

To disable:

public $timestamps = false;

Conclusion

Models and Eloquent ORM provide a powerful and intuitive way to interact with databases in Laravel. By using expressive syntax and built-in relationships, Eloquent simplifies database operations while maintaining clean, readable, and maintainable code.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes