I have a routes group in Laravel that gets a parameter like below:
Route::group(['prefix' => '{ProjectCode}'], function () {
Route::get('/categories', 'CategoriesController@Categories');
Route::get('/add-category', 'CategoriesController@AddCategory');
});
The ProjectCode
is an id, that is used to get some data from the database
I want to pass the retrieved data to controllers that they are in sub of the route group and avoid getting data in every function in controller
You may use "Implicit/Explicit Route Model Binding", assuming you have Project
model, you can have this controller method (use camelCase for parameters and controllers' methods name not 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)
{
//
}
}
You may wish to use your own resolution binding, override the resolveRouteBinding
on your model:
/**
* 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();
}
See Laravel docs for more info.