4

So I'm working on an admin interface. I have a route set up like so:

Route::controllers([
    'admin' => 'AdminController',
]);

Then I have a controller with some methods:

public function getEditUser($user_id = null)
{
    // Get user from database and return view
}

public function postEditUser($user_id = 0, EditUserRequest $request)
{
    // Process any changes made
}

As you can see, I'm using method injection to validate the user input, so URL's would look like this:

http://example.com/admin/edit-user/8697

A GET request would go to the GET method and a POST request to the POST method. The problem is, if I'm creating a new user, there won't be an ID:

http://examplecom/admin/edit-user/

Then I get an error (paraphrased):

Argument 2 passed to controller must be an instance of EditUserRequest, none given

So right now I'm passing an ID of 0 in to make it work for creating new users, but this app is just getting started, so am I going to have to do this throughout the entire application? Is there a better way to pass in a validation method, and optionally, parameters? Any wisdom will be appreciated.

3
  • You should probably create another method for the create of the user. PUT should be used for update while POST should be used for create so: putEditUser and postCreateUser Commented Apr 1, 2015 at 19:29
  • 1
    What about if you reverse the order? postEditUser(EditUserRequest $request, $user_id = null) Commented Apr 1, 2015 at 20:50
  • @lukasgeiter Huh, I thought I tried that already, but it works like a charm (reversing the order). Post that as an answer and I'll accept it. Also, another method I was using was to just pass in the user_id as a hidden field, and have no user_id parameter on the POST method. Commented Apr 1, 2015 at 21:13

1 Answer 1

3

You can reverse the order of your parameters so the optional one is a the end:

public function postEditUser(EditUserRequest $request, $user_id = null)
{

}

Laravel will then resolve the EditUserRequest first and pass nothing more if there's no user_id so the default value will kick in.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.