Maxime
Maxime

Reputation: 154

Append Laravel model namespace as table prefix

I am working on a Laravel 5.5 project that contains multiple "applications": Articles, Notes, Photos, etc.

Each application should have its own directory/namespace, containing its models:

app/
    Blog/
        Article.php
        Category.php
    Notes/
        Note.php
        Category.php
    ...

When I run this command php artisan make:model --migration Blog/Category, it successfully creates a app/Blog/Category.php model and App\Blog namespace, but the associated migration creates a table named category, instead of blog_category. Which is problematic since I also need to create app/Notes/Category.php.

Is there a trick to prefix category tables ? Would Laravel resolves those tables if I manually change their names, or must I add a $table attribute in each model?

Isn't it surprising that Model namespace and table name are not related by prefix, following Laravel logic?

Upvotes: 1

Views: 1551

Answers (3)

Ali Rasheed
Ali Rasheed

Reputation: 2817

Following the answer for the_hasanov:

I have done some changes and works great.

namespace App\Traits;

use Illuminate\Support\Str;

trait ModelTrait
{

    /**
     * Scopped Variables
     */
    protected $table_prefix              =  "prefix_";

    /**
     * Appends prefix to table name
     * 
     * @return $table
     */
    public function getTable() {

        $model                           =  explode("\\", get_class($this));
        $model                           =  Str::lower(array_pop($model));

        if (!isset($this->table)) $this->setTable(Str::plural($this->table_prefix . $model));

        return $this->table;

    }

}

Add a trait like this and in model use it like this:

class Model {
    use ModelTrait;
}

Upvotes: 0

the_hasanov
the_hasanov

Reputation: 843

this trait can help you

use Illuminate\Support\Str;

trait TableNameResolver
{
    public $base_namespace=__NAMESPACE__;

    public function getTable()
    {
        if (! isset($this->table)) {
           $this->setTable(str_replace(
                '\\', '', Str::snake(Str::plural(trim(str_after(get_class($this),trim($this->base_namespace,'\\')),'\\')))
            ));
        }
        return $this->table;
    }
}

Upvotes: 1

There is two choice to solve it:

  • Make the model with BlogArticle which will create blog_articles table
  • OR add $table="your table name" to every model

Upvotes: 2

Related Questions