4 Ways to Define Model in Eloquent (Laravel)

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Laravel’s Eloquent ORM provides an elegant way to interact with databases. Here, we will explore different ways to define models using Eloquent, diving into a range of solutions fitting various scenarios.

Approach 1: Basic Model Creation

Defining a simple model linked to a database table:

  1. Create a new model using the artisan command php artisan make:model ModelName.
  2. Edit the generated model file to fit your needs.
  3. If necessary, set the $table property if the table name does not follow Laravel’s naming convention.

Example:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ModelName extends Model
{
    protected $table = 'custom_table_name';
}

This creates a basic model. Laravel assumes the table name by pluralizing the class name unless you specify otherwise.

Approach 2: Defining Relationships

Use models to define relationships between database tables:

  1. Define methods within the model reflecting the relationships (e.g., one-to-one, one-to-many).
  2. Use Eloquent relationship functions, such as hasOne, hasMany, belongsTo, and belongsToMany.
  3. Return the result of the relationship function within your method.

Example:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

This provides a way to easily retrieve related models.

Approach 3: Accessors & Mutators

Define custom attribute getters and setters to modify model data:

  1. Create methods prefixed with get to define an accessor or set for a mutator.
  2. Follow the method name with the attribute name in StudlyCase followed by Attribute.
  3. For accessors, return the modified attribute. For mutators, modify the attribute’s value directly.

Example:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function getFullNameAttribute()
    {
        return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
    }

    public function setFirstNameAttribute($value)
    {
        $this->attributes['first_name'] = strtolower($value);
    }
}

Accessors and mutators allow you to manipulate model data on-the-fly.

Approach 4: Global Scopes

Apply a query scope to all queries for a model:

  1. Create a new class implementing the Scope interface.
  2. Define an apply method within it.
  3. Attach the scope to a model using the addGlobalScope method.

Example:

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class AgeScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('age', '>', 18);
    }
}

// In your model

namespace App\Models;

use App\Scopes\AgeScope;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected static function booted()
    {
        static::addGlobalScope(new AgeScope);
    }
}

Global scopes affect how models are retrieved across the whole application.

Conclusion

Defining models in Laravel’s Eloquent can be approached from various angles. Simple models are a breeze with Laravel’s naming conventions, while relationships provide robust methods to interact with related data. Accessors and mutators grant fine-tuned control over data access and manipulation, and global scopes offer a way to enforce a common query constraint. Clearly understanding these methods paves the way for an organized and efficient database integration within your application.