Sling Academy
Home/PHP/4 Ways to Define Model in Eloquent (Laravel)

4 Ways to Define Model in Eloquent (Laravel)

Last updated: January 16, 2024

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.

Next Article: How to use custom table name in Eloquent (Laravel)

Previous Article: Laravel Query Builder: Select rows where IDs are in an array

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array