Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel get Model by Table Name

Tags:

php

laravel

Is there any way to get a model by table name?

For example, I have a "User" model, its table is defined as protected $table = "users"

Now, what I want to do is to get the model by table name which is equal to "users".

This function is more like the reverse of Model::getTable();

I have searched everywhere but I could not find a solution, perhaps I might be missing something simple?

EDIT

I am building something like an API :

Route::get('/{table}', 'ApiController@api');
Route::get('/{table}/filter', 'ApiController@filter');
Route::get('/{table}/sort', 'ApiController@sort');
Route::get('/{table}/search', 'ApiController@search');

so in the address bar, for example when I search for the "users", I could just hit on the URL:

api/users/search?id=1

then on the controller, something like:

public function search(){
  // get all the params

  // get the model function
  $model = //function to get model by table name

  // do some filtering, then return the model
  return $model;
}
like image 958
Defy Avatar asked May 29 '16 18:05

Defy


1 Answers

Maybe something like this will help you:

$className = 'App\\' . studly_case(str_singular($tableName));

if(class_exists($className)) {
    $model = new $className;
}
like image 114
Igor R Avatar answered Sep 24 '22 20:09

Igor R