Fırat Kaya
Fırat Kaya

Reputation: 97

How can I change database name conventions in Laravel?

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

Answers (3)

miken32
miken32

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

gre_gor
gre_gor

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

knubbe
knubbe

Reputation: 1182

You can use stubs for that. Also if you named your table in Pascal Case just use $table property in model which need to be sync with that table.

Upvotes: 0

Related Questions