Reputation: 97
I want to change the default database naming conventions in my Laravel app. By default, Laravel uses snake case for database table and column names. But I want to use Pascal Case for table names and i want to use camel Case for fields.
So a table name of Users
instead of users
, and field names createdAt
, updatedAt
, and deletedAt
instead of created_at
, updated_at
, and deleted_at
.
I know I can change these on a per-model basis using the $table
property but I'd like to change the default without having to modify each model.
Are there any settings like Symfony's NamingStrategy
in Laravel?
Upvotes: 3
Views: 756
Reputation: 42696
If you look at the code for Illuminate\Database\Eloquent\Model::getTable()
it's pretty straightforward:
public function getTable()
{
return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this)));
}
Same for Illuminate\Database\Eloquent\Concerns\HasTimestamps::getCreatedAtColumn()
:
public function getCreatedAtColumn()
{
return static::CREATED_AT;
}
So create your own class that extends Model
and override that behaviour:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Support\Str;
class Model extends BaseModel
{
const CREATED_AT = 'createdAt';
const UPDATED_AT = 'updatedAt';
const DELETED_AT = 'deletedAt';
public function getTable()
{
return $this->table ?? Str::pluralStudly(class_basename($this));
}
}
Now, just have your models extend App\Models\Model
instead of Illuminate\Database\Eloquent\Model
.
Upvotes: 4
Reputation: 6805
You can create a new model that you extend your models with.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class ModelWithPascalCase extends Model
{
const DELETED_AT = 'deletedAt';
const CREATED_AT = 'createdAt';
const UPDATED_AT = 'updatedAt';
public function getTable()
{
return $this->table ?? Str::pluralStudly(class_basename($this));
}
}
If you want to make Laravel generate your models extending this, you can do it by editing stubs.
Run
artisan stub:publish
then edit stubs/model.stub
by replacing Model
with your ModelWithPascalCase
.
After that, when you run
artisan make:model User
you get your User
model extended by ModelWithPascalCase
.
Upvotes: 2