How to return database table name in Laravel

前端 未结 11 563
执念已碎
执念已碎 2020-12-28 13:28

Is there a way that I can get the current database table in use by the model that I\'m in? I see that there is a table() function in Laravel/Database/Eloquent/model.php but

11条回答
  •  别那么骄傲
    2020-12-28 13:36

    I just wanted to add the following for people coming from search engines:

    In case you do not even want to instantiate the Model at all (faster?) :

    $model = 'App\User';
    $modelTable = str_replace('\\', '', Str::snake(Str::plural(class_basename($model))));
    dd($modelTable); // will return "users"
    

    That might look ugly but that's exactly how the getTable() method resolves it under the hood, so...

    You will need to use Illuminate\Support\Str; on top of your file.

    Addendum: implying you follow the framework's standards (i.e: Post model has posts table, User model has users table, etc)

提交回复
热议问题