Sling Academy
Home/PHP/How to use custom table name in Eloquent (Laravel)

How to use custom table name in Eloquent (Laravel)

Last updated: January 16, 2024

Introduction

Eloquent ORM (Object-Relational Mapper) is one of the essential features of Laravel that facilitates active record pattern implementation for working with the database. By convention, Eloquent will take the “snake_case” version of the class name and make it plural to determine the database table name. However, this convention might not suit everyone, especially when dealing with a legacy database or an application where table naming conventions differ. One of the most flexible features of Eloquent is the ability to customize your table names in the model. In this tutorial, we will guide you through the process of using custom table names in Eloquent step by step, covering everything from the basics to more advanced scenarios.

Basic Usage

The most straightforward case of defining a table name in Eloquent is by simply specifying a protected $table property within your model, like so:

class User extends Model {
    protected $table = 'my_custom_users';
}

With this change, Eloquent will use ‘my_custom_users’ instead of the default ‘users’ table when running queries on the User model.

Advanced Table Name Definition

While specifying a custom name directly is simple and straightforward, sometimes applications may need to determine the table name at runtime. You can override the getTable method within your model to achieve this:

class User extends Model {
    public function getTable() {
        return 'prefix_' . parent::getTable();
    }
}

This code dynamically sets the table name by prefixing it, which could be useful in a multi-tenant system where each tenant has its own table prefix.

Working with Schema Builder

When creating migrations, you should ensure that you use the correct table name in schema operations:

Schema::create('my_custom_users', function (Blueprint $table) {
    // Define the schema for the my_custom_users table
});

Remember to keep the table name in the migration consistent with what is defined in the model.

Relationships With Custom Table Names

Custom table names also require attention when defining relationships. You’ll often need to specify the custom table name in the relationship methods:

class Post extends Model {
    public function author() {
        return $this->belongsTo(User::class, 'author_id', 'id');
    }
}

By default, the belongsTo method would try to link to the ‘users’ table. It will work seamlessly with the ‘my_custom_users’ table without additional changes since Eloquent handles this internally based on your User model configuration.

Querying With Custom Table Names

When querying models with a custom table name, you don’t have to specify the table name directly. Queries like the following will work out of the box:

$users = User::where('active', 1)->get();

This will correctly query against the ‘my_custom_users’ table.

Conclusion

This tutorial has explored the various ways of using custom table names in Laravel’s Eloquent ORM. You’ve learned how to define custom table names explicitly, how to dynamically set table names, and how to accommodate custom table names when defining relationships and writing migrations. Following these guidelines will give you the flexibility needed to work with any database schema while leveraging the power of Eloquent.

Now when you dive into your Laravel projects, remember: conventions are tools, not rules. Eloquent’s adaptability with custom table names is a perfect illustration of how Laravel is designed with developers in mind, being both powerful and flexible.

Next Article: Eloquent: Creating table with auto-incrementing ID

Previous Article: 4 Ways to Define Model in Eloquent (Laravel)

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