support@codebucket.net

How to call a GET request in Laravel without any package

How to call a GET request in Laravel without any package

K. M. Shawkat Zamil | October 01, 2022

Hello Developers,

Sometimes you find that you need to call a simple GET request to fetch any data. You see in Laravel, to call any API different types of packages are used. But there is an efficient to call any GET request without any package. In this demonstration, you will see that.

 

For that, first, you need to create a controller, I have created a TestController by the following command:

 

php artisan make:controller

 

After that, you need to define a route.

 

<?php

use App\Http\Controllers\TestController;

Route::get('/get_data', [TestController::class, 'get_data'])->name('get_data');

 

Now in the controller, you have to call file_get_contents() the function and wrap it with json_decode(). The code is given below:

 

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    public function get_data(){
        $json = json_decode(file_get_contents('https://countriesnow.space/api/v0.1/countries/positions'), true);

        return $json;
    }
}

 

Then you need to call the below command to start the project:

 

php artisan serve

 

After that, just call the route in the browser.

 

http://127.0.0.1:8000/get_data

 

Hope this might help you in your journey of development.

 

Read More: How to excel import with date format in Laravel

 

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.