moses toh
moses toh

Reputation: 13162

How to send different parameters to the same function? (laravel 5.3)

My view is like this :

...
<a class="btn btn-primary pull-right" style="margin-top: -10px;margin-bottom: 5px" href="{!! route('users.create.year', [$year]) !!}">
    Add New
</a>
...

...
@foreach($testArray as $key)
...
<a class="btn btn-primary btn-xs" href="{!! route('users.create.display.year', [$key['display'], $year]) !!}">
    <i class="glyphicon glyphicon-plus"></i>
</a>
...
@endforeach
...

My routes is like this :

Route::get('users/create/{year}', 'UserController@create')
     ->name('users.create.year');

Route::get('users/create/{display}/{year}', 'UserController@create')
     ->name('users.create.display.year');

My controller is like this :

public function create($display = null, $year)
{
    echo $display;
    echo $year;die();
    ...
}

When I call url like this : http://localhost/mysystem/public/users/create/2016

There exist error like this :

 1/1 ErrorException in UserController.php line 314: 
 Missing argument 2 for App\Http\Controllers\UserController::create() 

When I call url like this : http://localhost/mysystem/public/users/create/14144499452111901/2016` The result is like this :

14144499452111901
2016

Why when I call a url with one parameter there is an error?

Upvotes: 1

Views: 1567

Answers (3)

Jeff
Jeff

Reputation: 166

Also you can use the Request object in the controller

public function create(Request $request) { $request->year; ... }

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

You should use optional parameters feature:

Route::get('users/create/{year}/{display?}', 'UserController@create')->name('users.create.year');

Use just one method, but with optional parameter:

public function create($year, $display = null)

Upvotes: 3

Tilak Raj
Tilak Raj

Reputation: 1499

Route::get('users/create/{year}', 'UserController@create')
     ->name('users.create.year');

Route::get('users/create/{display}/{year}', 'UserController@create')
     ->name('users.create.display.year');

You have defined two routes here and only one controller.

public function create($display = null, $year)
{
    echo $display;
    echo $year;die();
    ...
}

So when you do something like this http://localhost/mysystem/public/users/create/2016

it sends to the one that has more than one parameter.

Solution would be to create two controllers , one for each route

public function create($display = null, $year)
{
    echo $display;
    echo $year;die();
    ...
}

public function create( $year)
{
    echo $display;
    echo $year;die();
    ...
}

Upvotes: 0

Related Questions