moderith
moderith

Reputation: 33

Load in models dynamically in Laravel 5.1

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.

Upvotes: 3

Views: 2030

Answers (1)

Mehrdad Hedayati
Mehrdad Hedayati

Reputation: 1454

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'));

Upvotes: 7

Related Questions