Laravel - 从模型动态构建路径

时间:2017-09-06 20:14:23

标签: php mysql laravel-5 model

我正在尝试从下面的模型构建路线是代码。

$data = \App\Models\ModelName::all();

    if(!empty($data) && $data->count() >= 1)
    {
        foreach($data as $d)
        {
            Route::prefix('/'.$d['data_field'])->name($d['data_field'])->group(function(){
                Route::get('/', ucfirst($d['data_field']).'Controller@index');                  
            });
        }
    }

我不断收到$ d未定义的错误消息。有没有办法动态构建路由?

1 个答案:

答案 0 :(得分:1)

你需要将$d传递给闭包,因为它不存在于匿名函数的范围内:

Route::prefix('/'.$d['data_field'])
    ->name($d['data_field'])->group(function() use ($d) {
           Route::get('/', ucfirst($d['data_field']).'Controller@index');                  
    });