Thursday, March 2, 2017

How can I declare a route and a controller method that explicitly expect two query parameters like this?

I am pretty new in Laravel and I have the following problem.

I have to declare a route that handle requests like this:

http://laravel.dev/activate?email=myemail@gmail.com&token=eb0d89ba7a277621d7f1adf4c7803ebc

So this URL have to mantein this format (activate as resource and 2 query parameters in the form ?email and &token. This is not a REST URI. I need to use it in this way).

I need a route and a controller method that handle this kind of request.

I know that I can do something like this:

1) Into the routes/web.php file I declare a rout like this

Route::get('/activate','MyController@myMethod');

2) Into MyController I declare this method:

public function myMethod(Request $request) {

    if(Input::has('email') && Input::has('token')) {
        $email = $request->input('email');
        $token= $request->input('token');

        // DO SOMETHING USING $email AND $token
    }
    else {
        // SHOW ERROR PAGE
    }
}

But onestly I find it pretty horrible. I came from Java and using Spring framework I can specify in the mapping between the URL and the controller method that a method handle a request toward a resource and that to be handled some specific query paramer have to be passed. Otherwise (if these parameter are not present the HTTP GET request is not handled by the controller method).

I know that in Laravel I can do something like this using REST form of my URL, I think something like this:

For the route mapping:

Route::get('/activate/{email}/{token}', [ 'uses' => 'ActivationController@activate', 'as' => 'activate' ]);

And then the controller method will be something like this:

public function activate($email, $token) {
    // $email would be 'myemail@gmail.com'
    // $token would be 'eb0d89ba7a277621d7f1adf4c7803ebc'
    // do stuff...
}

But I can't use this kind of URI in this case (as specified the URL pattern have to be in the format:

http://laravel.dev/activate?email=myemail@gmail.com&token=eb0d89ba7a277621d7f1adf4c7803ebc

So I desire do something like this with this kind of URI. I don't wont to pass the Request $request object to my controller method and then extract the parameters from it but I want to have a controller method signature like this:

public function activate($email, $token) {

in which if all the expected parameters are not passed simply the request will not handled by this controller.

I prefer do it because for me is a neater approach (reading the controller signature another developer immediately know that this method is expecting).

And also because I want that malformed parameters are not handled by the method (so I can avoid to handle error cases like: the user not pass the 2 parameters).

How can I do something like this in Laravel? (if it is possible...)



via blablabla blablabla

Advertisement