DEV Community

Cover image for Laravel Models Demystified: Simplifying Database Operations
Asekhame Joel
Asekhame Joel

Posted on

Laravel Models Demystified: Simplifying Database Operations

Introduction

Before we dive right in, let me talk about Laravel, a powerful PHP framework, built on the MVC (Model-View-Controller) architecture, which organizes application logic into three interconnected components. In this architecture, the 'M' stands for 'Model' which is what we are focused on in this articles, a crucial element responsible for managing data interactions between your application and the database. Models act as the bridge that simplifies querying, retrieving, and manipulating data stored in database tables.

Laravel takes this a step further with its elegant implementation of Eloquent ORM (Object-Relational Mapping), offcourse we cannot talk about models, without knowing a little about Eloquent ORM, Eloquent provides an intuitive and expressive way to interact with your database, allowing developers to work with database records as if they were objects in their code instead of raw SQL queries. Each database table typically has a corresponding Model, which serves as the gateway for performing operations on that table.

Models in Laravel are more than just data handlers—they are the foundation of efficient database management. By encapsulating database logic within Models, Laravel ensures that your application remains clean, organized, and easy to maintain. Whether you're fetching data, inserting records, or updating information, Models streamline these tasks, making database interactions seamless and developer-friendly.

In this guide, we’ll dive deeper into the world of Models in Laravel, though it’s tempting to explore Views and Controllers as well, which makes up the MVC but for now, we’ll explore how Models simplify database operations.
Let’s embark on this journey to uncover the power of Laravel’s Models and discover how they can elevate your web development experience as a PHP developer!
Like my edo brothers would say……… Wa gima zẹ ẹdo (Lets Get Started)!!!!

What Are Models in Laravel?

From the introduction, I have or rather we’ve already covered about 70% of what Models are in Laravel. However, for the sake of clarity and a deeper understanding, let’s delve even further into this essential component of the framework.

At the core of Laravel’s MVC (Model-View-Controller) architecture is the Model, a pivotal element that dictates how data is structured, accessed, and manipulated within your application. Models in Laravel act as the primary interface for interacting with your database, serving as a direct representation of the tables stored within it. Each Model typically corresponds to a specific database table, enabling you to perform critical operations such as querying, updating, inserting, and deleting data using clean, expressive, and human-readable code.

But Models in Laravel are far more than just a conduit for database interactions. They are robust tools that allow you to encapsulate business logic, define relationships between tables, and enforce data validation rules all within a single, well-organized structure. By centralizing these functionalities within Models, Laravel promotes a modular and maintainable approach to development, ensuring that your application remains scalable and easy to manage as it evolves.

For instance, instead of scattering raw SQL queries throughout your application, you can leverage Eloquent ORM (Laravel’s built-in ORM) to interact with your database through Models. This approach not only simplifies your code but also makes it more intuitive and less prone to errors. Moreover, Models enable you to define relationships such as one-to-one, one-to-many, and many-to-many, making it seamless to work with related data across multiple tables.

In essence, Laravel Models are the backbone of your application’s data layer. They streamline database interactions, enhance code reusability, and provide a structured way to incorporate business logic. Whether you’re building a simple blog or a complex enterprise application, mastering Models is crucial to unlocking the full potential of Laravel as a PHP framework.

What Is the Purpose of Creating a Model in Laravel?

Models in Laravel are a big help in dealing with your application data. They simplify dealing with and organizing your application data, and make it easier to conduct database operations. But why use a Model in Laravel? Let’s break it down:

1. Direct Database Interaction
Models serve as the bridge between your application and your database. Instead of writing raw SQL queries scattered throughout your code, Models allow you to retrieve, create, update, and delete data using simple, expressive methods. This abstraction not only makes your code cleaner but also reduces the risk of errors and improves readability.

For example, instead of writing:

SELECT  FROM users WHERE id = 1;
Enter fullscreen mode Exit fullscreen mode

You can simply use:

$user = User::find(1);
Enter fullscreen mode Exit fullscreen mode

This approach is not only more intuitive but also aligns with Laravel’s philosophy of making development enjoyable.

2. Logical Data Organization
Each Model in Laravel represents a specific database table, such as User, Order, or Product. This gives your data a clear and meaningful structure that aligns with your application’s requirements. By organizing your data into Models, you create a logical representation of your database schema, making it easier to understand and maintain.

For instance, a User Model might represent a users table, while an Order Model corresponds to an orders table. This clear mapping ensures that your codebase is well-organized and easy to navigate.

3. Simplified Relationships
One of the most powerful features of Laravel Models is their ability to define and manage relationships between tables. Whether it’s a “one-to-many,” “many-to-many,” or “one-to-one” relationship, Models make it effortless to work with related data.

For example, if a user has many posts, you can define this relationship in the User Model:

public function posts() {
    return $this->hasMany(Post::class);
}
Enter fullscreen mode Exit fullscreen mode

Then, you can easily retrieve all posts for a user with:

$posts = User::find(1)->posts;
Enter fullscreen mode Exit fullscreen mode

This eliminates the need for complex joins and manual querying, saving you time and effort.

4. Built-in Data Security
Laravel Models come with built-in features to enhance data security and prevent common vulnerabilities. For example:

  • Mass Assignment Protection: Models allow you to specify which fields can be mass-assigned (e.g., via form submissions) using the $fillable or $guarded properties. This prevents unauthorized data manipulation.

  • Attribute Casting: You can define how certain attributes should be cast (e.g., converting JSON data to an array or boolean values to true/false), ensuring data consistency and security.

  • Validation: While validation is typically handled in controllers or form requests, Models can also encapsulate validation rules, making your data handling more robust.

5. Business Logic Encapsulation
Models aren’t just for database interactions they’re also a great place to encapsulate business logic. By adding methods to your Models, you can centralize logic related to specific data entities. For example, a User Model might include methods for calculating a user’s lifetime value, checking their subscription status, or sending a password reset email.

This approach keeps your controllers lean and ensures that your application’s logic is modular and reusable.

6. Improved Code Maintainability
By using Models, you adhere to the DRY (Don’t Repeat Yourself) principle. Instead of duplicating database logic across your application, you centralize it within Models. This makes your codebase easier to maintain, test, and scale as your application grows.

How to Create a Model in Laravel

Creating a Model in Laravel is a straightforward process that involves a few clear steps. Below, I will walk you through the entire process, from generating the Model to performing basic database operations like retrieving, inserting, updating, and deleting data. I will also include code examples and explanations to help you understand each step.

Step 1: Use the Artisan Command to Create a Model
Laravel provides a convenient Artisan command to generate Models. To create a Model, run the following command in your terminal:

php artisan make:model Article
Enter fullscreen mode Exit fullscreen mode

This command creates a new file named Article.php in the app directory. The file will look like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model {
    // 
}
Enter fullscreen mode Exit fullscreen mode

Here, the Article Model represents a database table (typically named articles). Laravel’s Eloquent ORM will automatically map this Model to the corresponding table.

Step 2: Create a Migration for the Model
In my previous article, I discussed migrations in detail. If you’re feeling unsure or need a refresher, I recommend revisiting that article for clarity. To create a database table for the Model, you’ll need to generate a migration. You can do this by running the following Artisan command:

php artisan make:migration create_articles_table
Enter fullscreen mode Exit fullscreen mode

This creates a migration file in the database/migrations directory. Open the file and define the table schema in the up() method:

public function up() {
    Schema::create('articles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('topic');
        $table->string('content');
        $table->timestamps(); // Adds created_at and updated_at columns
    });
}
Enter fullscreen mode Exit fullscreen mode

Run the migration to create the table in your database:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a Controller
To handle database operations, create a controller using the Artisan command:

php artisan make:controller ArticleController
Enter fullscreen mode Exit fullscreen mode

This generates a file named ArticleController.php in the app/Http/Controllers directory. Open the file and add methods for retrieving, inserting, updating, and deleting data:

<?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

class ArticleController extends Controller {

    // Retrieve all articles
    public function index() {
        $articles = Article::all();
        return view('homepage')->with('articles', $articles);
    }

    // Insert a new article
    public function insert() {
        $article = new Article;
        $article->topic = "View in Laravel";
        $article->content = "View is the data display at the user end.";
        $article->save();
        echo "Insert Successful!";
    }


    // Update an existing article
    public function update() {
        $article = Article::find(1); // Find the article with ID 1
        $article->topic = "Laravel";
        $article->save();
        echo "Update Successful!";
    }

    // Delete an article
    public function delete() {
        $article = Article::find(1); // Find the article with ID 1
        $article->delete();
        echo "Delete Successful!";
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Create a View
Create a view file named homepage.blade.php in the resources/views directory. This view will display the list of articles:

<!DOCTYPE html>
<html>
<head>
    <title>Models by Joel Asekhame</title>
    <style>
        body {
            font-size: 20px;
        }
    </style>
</head>
<body>
    <h2>Articles Topics</h2>
    <ol>
        @foreach($articles as $article)
            <li>{{ $article->topic }}</li>
        @endforeach
    </ol>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 5: Define Routes
Open the routes/web.php file and define routes for the controller methods:

use App\Http\Controllers\ArticleController;

// Homepage route to display articles
Route::get('/', [ArticleController::class, 'index']);

// Routes for insert, update, and delete operations
Route::get('/insert', [ArticleController::class, 'insert']);
Route::get('/update', [ArticleController::class, 'update']);
Route::get('/delete', [ArticleController::class, 'delete']);
Enter fullscreen mode Exit fullscreen mode

Step 6: Run the Application
Start the Laravel development server using the following command:

php artisan serve
Enter fullscreen mode Exit fullscreen mode

Example Outputs

  1. Index Function (Retrieve Data):
    Displays a list of articles on the homepage.
    Image description

  2. Insert Function:
    Adds a new article to the database and displays "Insert Successful!"
    Image description
    Image description

  3. Update Function:
    Updates the topic of the article with ID 1 and displays "Update Successful!"
    Image description
    Image description

  4. Delete Function:
    Deletes the article with ID 1 and displays "Delete Successful!"
    Image description
    Image description

Top comments (0)