1

I'm working on a Laravel 5.6 app and have the following two API routes:

Route::resource('/partners', 'API\Partners\PartnersController');

Route::resource('/partners/{id}/sales-team', 'API\Partners\SalesTeamController');

In both of the controllers I am referencing a custom middleware 'VerifyUserOwnsTeam' in the construct method.

To get the resource ID from the request in the middleware I previously had:

$request->route('partner')

This worked a URL such as:

/api/partners/1

However, I am now calling a new end point such as:

/api/partners/1/sales-team

In my middleware the request route param for partner is null. If I change the reference to be:

$request->route('id')

Then it works for the latter endpoint, but fails on the first for a null value.

Any idea how to get this consistent?

Lovelock
  • 7,689
  • 19
  • 86
  • 186

3 Answers3

1

I use laravel 8 and got solved in my case. I have put the param id from the router to function in my controller. Then passing the id with compact function to use on my view.

Here's the code example

My router:

Route::resource('stock/{id}', StockController::class);

My controller:

public function index($id, Request $request)
{
    return View::make("pages.stock.index", compact('id'));
}

My view:

{{$id}}

Idk this is works or not for your case, but I hope you get some clue.

0

you need to change your first route to accept an id:

Route::resource('/partners/{id?}', 'API\Partners\PartnersController');

Ali
  • 3,568
  • 2
  • 24
  • 31
  • The resource route already sets the id as an accepted parameter. – Lovelock Mar 15 '18 at 16:47
  • yeah sorry about that, just noticed it's a resource route – Ali Mar 15 '18 at 16:48
  • can't you name your route param to `partner`? `Route::resource('/partners/{partner}/sales-team', 'API\Partners\SalesTeamController');` – Ali Mar 15 '18 at 16:54
  • Hey nice idea, I tried it a few mins ago too but didn't work. Gave it another go and what d'ya know! Worked like a charm, cheers either way :) – Lovelock Mar 15 '18 at 16:59
-1

For all searchers: For resources in edit/update/delete actions you can access id of the model inside Request classes using

$this->get('id')