Dronax
Dronax

Reputation: 289

Get model table name without query

I have a package media library by spatie. I need to get table name of the model.

I know that I can do this:

public function getPath(Media $media) {
     $name = (new $media->model())->getTable()
}

But this creates a new query. I don't need to create an extra query on database. In table media, I have a column a model_type, where records can be like this: App\ModelName. Maybe I can get names of the model without a query?

Upvotes: 1

Views: 808

Answers (2)

Viktar Pryshchepa
Viktar Pryshchepa

Reputation: 343

There is an answer in laravel framework github: https://github.com/laravel/framework/issues/1436 . So it seems you will need to extend Media model. Example from github

class BaseModel extends Eloquent {

    public static function getTableName()
    {
        return with(new static)->getTable();
    }

}

class User extends BaseModel {

}


User::getTableName();

Upvotes: 2

jlos
jlos

Reputation: 1050

I don't think "new model()" created a query on the database, it just spawns a new object instance of the model class. I don't know the library by heart, but given that it's a Spatie library, it probably functions very similar like Eloquent does, which has the same behaviour.

Upvotes: 0

Related Questions