Hello I'm creating API using REST and Laravel following this article.
Everything works well as expected.
Now, I want to map GET request to recognise variable using "?".
For example: domain/api/v1/todos?start=1&limit=2
Below is the content of my routes.php :
Route::any('api/v1/todos/(:num?)', array(
'as' => 'api.todos',
'uses' => 'api.todos@index'
));
my controllers/api/todos.php :
class Api_Todos_Controller extends Base_Controller {
public $restful = true;
public function get_index($id = null) {
if(is_null($id)) {
return Response::eloquent(Todo::all(1));
} else {
$todo = Todo::find($id);
if (is_null($todo)) {
return Response::json('Todo not found', 404);
} else {
return Response::eloquent($todo);
}
}
}
}
How to recognise get parameter using "?" ?
It's quite simple - and also applicable to POST requests. I haven't tested on other Laravel versions but on 5.3-5.7 you reference the query parameter as if it were a member of the
Request
class
.1. Url
http://example.com/path?page=2
2. In a routes callback or controller action using magic method Request::__get()
3. Default values
We can also pass in a default value which is returned if a parameter doesn't exist. It saves us from this ternary magic
4. Using request function
The default parameter is optional therefore one can omit it
5. Using Request::query()
6. Using the Request facade
You can read more in the official documentation https://laravel.com/docs/5.7/requests
In laravel 5.3
$start = Input::get('start');
returnsNULL
To solve this
We have similar situation right now and as of this answer, I am using laravel 5.6 release.
I will not use your example in the question but mine, because it's related though.
I have route like this:
Then in your controller method, make sure you include
and this should be above your controller, most likely a default, if generated using
php artisan
, now to get variable from the url it should look like this:Regardless of the HTTP verb, the input() method may be used to retrieve user input.
https://laravel.com/docs/5.6/requests#retrieving-input
Hope this help.
This is the best practice. This way you will get the variables from GET method as well as POST method
In laravel 5.3
I want to show the get param in my view
Step 1 : my route
Step 2 : Write a function inside your controller
Now you're returning the parameter that you passed to the view
Step 3 : Showing it in my View
Inside my view you i can simply echo it by using
So If you have this in your url
http://127.0.0.1/yourproject/refral/this@that.com
Then it will print this@that.com in you view file
hope this helps someone.
Query params are used like this: