Laravel

Understanding Laravel Models: A Comprehensive Guide

Apr 29, 2025, 1:53 PM
Blog Thumbnail

Introduction

Laravel models are at the heart of the MVC (Model-View-Controller) architecture. They provide an elegant way to interact with your database using Laravel’s Eloquent ORM, simplifying CRUD operations and allowing you to focus on your application’s business logic.

Creating a Laravel Model

To create a model, run the following Artisan command:

php artisan make:model Post

This command creates a file at app/Models/Post.php (or app/Post.php in older versions). Here’s an example:

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // Specify the fields that can be mass-assigned
    protected $fillable = ['title', 'body'];
}

Using the Model (CRUD Operations)

Creating Records

// Using create() method
Post::create([
    'title' => 'Hello World',
    'body'  => 'This is my first blog post.',
]);

// Using a new instance and save()
$post = new Post;
$post->title = 'Another Post';
$post->body  = 'Content of the post goes here.';
$post->save();

Reading Records

// Get all posts
$posts = Post::all();

// Find a post by primary key
$post = Post::find(1);

// Retrieve records matching specific criteria
$posts = Post::where('title', 'Hello World')->get();

Updating Records

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

Deleting Records

$post = Post::find(1);
$post->delete();

// Or delete directly by id
Post::destroy(1);

Additional Specifications

  • Relationships: Easily define one-to-many, many-to-many, and other relationships.
  • Mass Assignment Protection: Use $fillable or $guarded to secure your models.
  • Query Scopes: Create reusable query logic within your models.
  • Accessors & Mutators: Automatically format attribute values when retrieving or saving.
  • Caching & Performance: Integrate caching strategies to optimize database interactions.
  • Model Events: Hook into the model lifecycle to execute actions like logging or notifications.

Removing a Model File

To remove a model file from your project, simply delete the corresponding PHP file (e.g., app/Models/Post.php).

Conclusion

Laravel models simplify database operations and ensure your application remains clean and maintainable. Their extensive functionalities—from CRUD operations to advanced relationships and event handling—make them an indispensable part of modern Laravel development.