Lovelock
Lovelock

Reputation: 8105

Laravel request helper in URL to get ID / Resource ID

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?

Upvotes: 1

Views: 2482

Answers (3)

user15909588
user15909588

Reputation:

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.

Upvotes: 1

Volodymyr Sitdikov
Volodymyr Sitdikov

Reputation: 424

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

$this->get('id') 

Upvotes: -1

Ali
Ali

Reputation: 3676

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

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

Upvotes: 0

Related Questions