0

I have the following controller:

class CustomerController extends Controller
{
    public function index(int $customerId = 0) : Renderable
    {
        dd($customerId);

...

And I'm requesting it by the following url http://localhost/customers?customerId=123. I would like to catch customerId as int. But It always gives 0 (default value the for method's signature). Ok, I can do something like:

$customerId = $request->input('customerId');

But the approach with getting parameter from the method's signature is more attractive for me.

I have seen this answer. It looks like very nice! But it does not work for my case. Why? Where is the mistake? Thank you for attention!

Update

Here I will show my routes definitions:

Auth::routes(['register' => false, 'reset' => false]);

Route::middleware('auth')->group(function () {
    Route::resource('customers', 'CustomerController');
});

Aleksej_Shherbak
  • 2,757
  • 5
  • 34
  • 71

2 Answers2

1

AFAIK Laravel doesn't inject parameters this way. If such URI is really needed - you should manually inspect request input for your variables.

If you want to use controller as written, you should use route parameters (e.g. /customers/{id}) instead of parameters after ?. By default resource controllers use index() for displaying all entities and show() for displaying only one entity.

If you use Eloquent, you can also inject Customer model, e.g.

public function index(Customer $customer) : Renderable

Customer will be automatically found by id and injected in controller method.

Weisskopf
  • 101
  • 1
  • 3
1

If you want to use the Resource Route you have to pass the customerID parameter like below. And also you have to use one of these methods: show, edit,update or destroy in your controller.

Route::resource('customers', 'CustomerController')->parameters([
    'customers' => 'customerId'
]);

For more details: https://laravel.com/docs/5.7/controllers#resource-controllers

Md. Miraj Khan
  • 377
  • 3
  • 15
  • Ok, I have override my route according to given example. But works `show` method instead of index with `customerId` parameter. I'm using `/customers/123` and I expect that Laravel think that it's `/customers/{customerId}` but Laravel shows me `show` method. – Aleksej_Shherbak Nov 09 '19 at 10:17
  • To have the ability to catch URL parameter via `function index(int $customerId = 0)` I need to set `parameters` as you specified me in the answer, right? Then I have to request `/customers/123`, and I will be able to catch the parameter, right? But I have resource controller, that has predefined routes. It has `show` method with route `/customer/`. It will overlay my index. – Aleksej_Shherbak Nov 09 '19 at 18:48
  • 1
    Yes! that's correct. You will not be able to catch the param in the index() method. You have to use the show or edit method. – Md. Miraj Khan Nov 09 '19 at 18:57
  • Thank you. I have to reorganize my controller. – Aleksej_Shherbak Nov 09 '19 at 18:59