In Laravel, you need to define the table name related with a model by using the $table
property within the model class. This is useful when the table does not created with the model. Following is the way of doing that.
Example
Suppose you have a table named custom_table
that doesn’t follow Laravel’s naming convention.
Step 1: Create the Model
If you don’t already have a model, create one using the make:model
Artisan command:
php artisan make:model CustomModel
Step 2: Define the Table Name
Open the generated model file (e.g., CustomModel.php
) and set the $table
property to the name of your database table:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class CustomModel extends Model { use HasFactory; // Define the table name protected $table = 'custom_table'; }
When is $table
Needed?
- When your table name does not match Laravel’s naming convention (e.g.,
posts
forPost
model). - When using a different naming scheme (e.g.,
tbl_users
for aUser
model). - For legacy databases where table names cannot be changed.
Defining Relationships
After defining the $table
property, you can still use Laravel’s relationship methods like hasOne
, hasMany
, etc., as usual. The $table
property ensures Laravel uses the correct table for queries.
Ravindra is a passionate full stack developer and dedicated blogger with a flair for crafting user-friendly web applications and insightful articles. With expertise spanning front-end and back-end technologies, Ravindra brings ideas to life through innovative coding solutions.