mardi 6 octobre 2015

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire