Load in models dynamically in Laravel 5.1

三世轮回 提交于 2020-01-14 18:44:27

问题


I'm new to Laravel and frameworks in general, and am having trouble with something I assume has an easy answer

I'm building an admin panel, and I want to load in tables based on the route given. In my Routes file I have:

Route::get('/admin/{table}', 'AdminController@table');

In my AdminController I have:

public function table()
{
    if (file_exists(app_path() . '/' . $table . '.php')){
        $data = $table::all();
    } else {
        abort(404);
    }

    return view('admin.pages.' . $table, compact($data));
}

When I go to /admin/table1 this I get this error:

FatalErrorException in AdminController.php line 20:
Class 'table1' not found

I pretty sure this doesn't work because I'm not allowed to have $variables as class names like $table::all(). In the end what I am trying to avoid is having to do something like this:

public function table1()
{
    $data = table1::all();
    return view('admin.pages.table1', compact($data));
}

public function table2()
{
    $data = table2::all();
    return view('admin.pages.table2', compact($data));
}

public function table3()
{
    $data = table3::all();
    return view('admin.pages.table3', compact($data));
}

...

Any advice would be appreciated.


回答1:


public function table($table)
{
    $class = 'App\\' . $table;
    if (class_exists($class)) {
        $data = $class::all();
    } else {
        abort(404);
    }

    return view('admin.pages.' . $table, compact($data));
}

Of course if you want to use simpler route parameters like users instead of User you can do like so:

$class = 'App\\' . ucwords(rtrim($table,'s'));


来源:https://stackoverflow.com/questions/32981766/load-in-models-dynamically-in-laravel-5-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!