[php] Getting GET "?" variable in laravel

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 "?" ?

This question is related to php api rest laravel

The answer is


In laravel 5.3

I want to show the get param in my view

Step 1 : my route

Route::get('my_route/{myvalue}', 'myController@myfunction');

Step 2 : Write a function inside your controller

public function myfunction($myvalue)
{
    return view('get')->with('myvalue', $myvalue);
}

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

{{ $myvalue }}

So If you have this in your url

http://127.0.0.1/yourproject/refral/[email protected]

Then it will print [email protected] in you view file

hope this helps someone.


Query params are used like this:

use Illuminate\Http\Request;

class MyController extends BaseController{

    public function index(Request $request){
         $param = $request->query('param');
    }

This is the best practice. This way you will get the variables from GET method as well as POST method

    public function index(Request $request) {
            $data=$request->all();
            dd($data);
    }
//OR if you want few of them then
    public function index(Request $request) {
            $data=$request->only('id','name','etc');
            dd($data);
    }
//OR if you want all except few then
    public function index(Request $request) {
            $data=$request->except('__token');
            dd($data);
    }

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:

Route::name('your.name.here')->get('/your/uri', 'YourController@someMethod');

Then in your controller method, make sure you include

use Illuminate\Http\Request;

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:

  public function someMethod(Request $request)
  {
    $foo = $request->input("start");
    $bar = $request->input("limit");

    // some codes here
  }

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.


In laravel 5.3 $start = Input::get('start'); returns NULL

To solve this

use Illuminate\Support\Facades\Input;

//then inside you controller function  use

$input = Input::all(); // $input will have all your variables,  

$start = $input['start'];
$limit = $input['limit'];

It is not very nice to use native php resources like $_GET as Laravel gives us easy ways to get the variables. As a matter of standard, whenever possible use the resources of the laravel itself instead of pure PHP.

There is at least two modes to get variables by GET in Laravel ( Laravel 5.x or greater):

Mode 1

Route:

Route::get('computers={id}', 'ComputersController@index');

Request (POSTMAN or client...):

http://localhost/api/computers=500

Controler - You can access the {id} paramter in the Controlller by:

public function index(Request $request, $id){
   return $id;
}

Mode 2

Route:

Route::get('computers', 'ComputersController@index');

Request (POSTMAN or client...):

http://localhost/api/computers?id=500

Controler - You can access the ?id paramter in the Controlller by:

public function index(Request $request){
   return $request->input('id');
}

I haven't tested on other Laravel versions but on 5.3-5.8 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 route callback or controller action using magic method Request::__get()

Route::get('/path', function(Request $request){
 dd($request->page);
}); 

//or in your controller
public function foo(Request $request){
 dd($request->page);
}

//NOTE: If you are wondering where the request instance is coming from, Laravel automatically injects the request instance from the IOC container
//output
"2"

3. Default values

We can also pass in a default value which is returned if a parameter doesn't exist. It's much cleaner than a ternary expression that you'd normally use with the request globals

   //wrong way to do it in Laravel
   $page = isset($_POST['page']) ? $_POST['page'] : 1; 

   //do this instead
   $request->get('page', 1);

   //returns page 1 if there is no page
   //NOTE: This behaves like $_REQUEST array. It looks in both the
   //request body and the query string
   $request->input('page', 1);

4. Using request function

$page = request('page', 1);
//returns page 1 if there is no page parameter in the query  string
//it is the equivalent of
$page = 1; 
if(!empty($_GET['page'])
   $page = $_GET['page'];

The default parameter is optional therefore one can omit it

5. Using Request::query()

While the input method retrieves values from entire request payload (including the query string), the query method will only retrieve values from the query string

//this is the equivalent of retrieving the parameter
//from the $_GET global array
$page = $request->query('page');

//with a default
$page = $request->query('page', 1);

6. Using the Request facade

$page = Request::get('page');

//with a default value
$page = Request::get('page', 1);

You can read more in the official documentation https://laravel.com/docs/5.8/requests


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to api

I am receiving warning in Facebook Application using PHP SDK Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Failed to load resource: the server responded with a status of 404 (Not Found) css Call another rest api from my server in Spring-Boot How to send custom headers with requests in Swagger UI? This page didn't load Google Maps correctly. See the JavaScript console for technical details How can I send a Firebase Cloud Messaging notification without use the Firebase Console? Allow Access-Control-Allow-Origin header using HTML5 fetch API How to send an HTTP request with a header parameter? Laravel 5.1 API Enable Cors

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory