How to Specify a Custom Table Name for a Laravel Model
This guide explains why Laravel automatically pluralizes model names to table names, the problems it can cause, and how to override the default by adding a protected $table property in the model class to map the model to a custom table name.
When creating a Model in Laravel, the framework automatically derives the corresponding database table name by pluralizing the model name, which works in most cases but can cause issues with irregular nouns or when a different table name is required.
Running the command php artisan make:model Customer generates a Customer model and expects a table named customers in the database.
To use a custom table name, add a protected $table property inside the model class, specifying the exact table you want the model to interact with.
<code><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model {
protected $table = 'customer';
}
</code>This code forces Laravel to map the Customer model to the customer table instead of the default customers table. The same adjustment should be applied to any model where the automatic pluralization does not match the intended table name.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.