1

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

STA
  • 30,729
  • 8
  • 45
  • 59
Meraj
  • 35
  • 5
  • create a middleware that will be easier. – shyammakwana.me Jun 28 '20 at 17:13
  • Have you tried [Implicit](https://laravel.com/docs/7.x/routing#implicit-binding) or [Explicit](https://laravel.com/docs/7.x/routing#explicit-binding) route binding? This is typically how models are pulled before a controller. – LLai Jun 28 '20 at 17:17
  • @LLai thanks , I will try it, this is ok to use it in multiple groups as a sub ? I mean declare it in a group and use it in other sub groups – Meraj Jun 28 '20 at 17:24
  • @shyammakwana.me thanks , but how can I get the returned data and pass them into all controllers in group route? – Meraj Jun 28 '20 at 17:26
  • This I'm not 100% sure on. I've typically used route binding directly in routes and not in groups, but I'm guessing it will work – LLai Jun 28 '20 at 17:26
  • Do you have a model named `App\ProjectCode`? because afaik, your code should work as it is – Salim Djerbouh Jun 28 '20 at 17:46
  • no, I haven't created that , but if I create it how can I use it to pass the got data to controllers? – Meraj Jun 28 '20 at 17:53
  • @Meraj in middleware write your value to `$request` like `$request->data = $dataFromModel`. then it will be available in following routes or nearly anywhere – shyammakwana.me Jun 29 '20 at 10:40

1 Answers1

1

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.

Hafez Divandari
  • 8,381
  • 4
  • 46
  • 63