LARAVEL - CURL REQUEST EXAMPLE USING IXUDRA/CURL PACKAGE

Curl is a way we can connect to a URL from our code and get a response from it. If we are using PHP then we can write simple get, post, put and delete using PHP curl itself,  or we can install this package then it will be easy for us to use because compared to normal curl syntax is simple.

Install ixudra/curl Package:

composer require ixudra/curl

Configure Curl

Open the config/app.php and add the below codes to configure curl

'providers' => [
....
Ixudra\Curl\CurlServiceProvider::class,
],

'aliases' => [
....
'Curl' => Ixudra\Curl\Facades\Curl::class,
]

Creating routes

Creating the routes now

Route::get('get-curl', 'HomeController@getCURL');

Adding the controller method

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Ixudra\Curl\Facades\Curl;
class HomeController extends Controller
{
    public function getCURL()
    {
        $response = Curl::to('http://google.com')
                            ->get();
        dd($response);
    }
}

Curl Post Request

public function getCURL()
{
    $response = Curl::to('https://example.com/posts')
                ->withData(['title'=>'Test', 'body'=>'sdsd', 'userId'=>1])
                ->post();
    dd($response);
}

Curl Put Request

public function getCURL()
{
    $response = Curl::to('https://example.com/posts/1')
                ->withData(['title'=>'Test', 'body'=>'sdsd', 'userId'=>1])
                ->put();
    dd($response);
}

Curl Delete Request

public function getCURL()
{
    $response = Curl::to('https://example.com/posts/1')
                ->delete();
    dd($response);
}

Comments