如何将数据从路由组传递到其控制器?

How to pass data from routes group to its controllers?

我在 Laravel 中有一个路由组,它获取如下参数:

Route::group(['prefix' => '{ProjectCode}'], function () {
    Route::get('/categories', 'CategoriesController@Categories');
    Route::get('/add-category', 'CategoriesController@AddCategory');
});    

ProjectCode是一个id,用来从数据库中获取一些数据 我想将检索到的数据传递给它们位于路由组子目录中的控制器,并避免在控制器

中的每个函数中获取数据

您可以使用“Implicit/Explicit 路由模型绑定”,假设您有 Project 模型,您可以使用此控制器方法(参数使用驼峰式命名,控制器的方法名称不是 PascalCase):

Route::group(['prefix' => '{projectCode}'], function () {
    Route::get('/categories', 'CategoriesController@pategories');
    Route::get('/add-category', 'CategoriesController@addCategory');
});  

class CategoriesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param  Request  $request
     * @return \Illuminate\Http\Response
     */
    public function categories(\App\Project $projectCode)
    {
        //
    }
}

您可能希望使用自己的分辨率绑定,覆盖您模型上的 resolveRouteBinding

/**
* Retrieve the model for a bound value.
 *
 * @param  mixed  $value
 * @param  string|null  $field
 * @return \Illuminate\Database\Eloquent\Model|null
 */
public function resolveRouteBinding($value, $field = null)
{
    return $this->where($field ?? $this->getRouteKeyName(), $value)->first();
}

有关详细信息,请参阅 Laravel docs