SergioZhidkov
SergioZhidkov

Reputation: 381

Laravel route and optional params

I have some problems with my controller in laravel 5.4

My routes.php:

Route::group(array('domain' => '{subdomain}.site.com','as'=>'www::','middleware'=>array('web','varnish')), function() {

   Route::any('/material/{page?}/', [
      'as' => 'www_material', 'uses' => 'www\MaterialController@index'
   ]);

});

My controller:

<?php namespace App\Http\Controllers\www;

use App\Http\Controllers\Controller;
use View;
use DB;
use Illuminate\Http\Request;

class MaterialController extends Controller {

    public function index($subdomain, $page = 1, Request $request)
    {
        echo $subdomain;
        echo $page;
       //...some code
    }
}

There is no problems with url www.site.com/material/2/:

submodain = www,
page = 2

But www.site.com/material/:

Type error: Too few arguments to function App\Http\Controllers\www\MaterialController::index(), 2 passed and exactly 3 expected

I cant understand why this happend, because default value of page is 1.

Can someone help me? I cant solve this problem alone.

Thank you.

Upvotes: 0

Views: 56

Answers (2)

SamBremner
SamBremner

Reputation: 823

Your problem is the order the arguments are in the index method.

As the Request object will always be present put that first followed by $subdomain and then $page

As stated on the php website above example #5:

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

public function index(Request $request, $subdomain, $page = 1)
{
    echo $subdomain;
    echo $page;
   //...some code
}

Upvotes: 2

M K Garwa
M K Garwa

Reputation: 495

Try to remove trailing slash next to {page?} mentioned below and rerun the code.

Route::any('/material/{page?}', [
  'as' => 'www_material', 'uses' => 'www\MaterialController@index'

]);

Upvotes: 0

Related Questions