Appearance
HasTablePrefix Trait
The HasTablePrefix
trait automatically prefixes database table names based on the module name, providing better organization and preventing table name collisions between modules.
Features
This trait offers:
- Automatic detection of the module name from the class namespace
- Dynamic generation of prefixed table names
- Static access to table names for use in migrations
- Standardized naming convention for module tables
Methods
getTable(): string
Generates the table name with the appropriate prefix.
- Returns:
- The prefixed table name
- Behavior:
- Extracts the module name from the class namespace
- Converts the class name to snake_case and pluralizes it
- Looks up the table prefix from the module's configuration
- Prepends the prefix to the table name
getTableName(): string
Static method for accessing the table name from anywhere.
- Returns:
- The prefixed table name
- Behavior:
- Creates a new instance of the class and calls
getTable()
- Useful in migrations and other static contexts
- Creates a new instance of the class and calls
Configuration
To use this trait, add a table_prefix
key to your module's configuration:
php
// config/blog.php
return [
'table_prefix' => 'blog_',
// Other configuration...
];
If no prefix is configured, the trait will use an empty prefix.
Usage Example
Model Definition
php
<?php
namespace Modules\Blog\Models;
use Illuminate\Database\Eloquent\Model;
use ModuleManager\ModuleManager\Concerns\HasTablePrefix;
class Post extends Model
{
use HasTablePrefix;
// No need to specify $table property
protected $fillable = [
'title',
'content',
'author_id',
];
}
Migration Usage
php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Modules\Blog\Models\Post;
class CreatePostsTable extends Migration
{
public function up(): void
{
// Will create "blog_posts" table
Schema::create(Post::getTableName(), function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->foreignId('author_id');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists(Post::getTableName());
}
}
Notes
- Using this trait eliminates the need to manually define the
$table
property in models - Table names are standardized across your module, reducing naming inconsistencies
- The trait works well in multi-module applications to prevent table name conflicts
- It's recommended to use the static
getTableName()
method in migrations for consistency