How to perform CURL requests using ixudra/curl in Laravel
The ixudra package in Laravel provides an efficient way to use curl to perform
To perform get and post requests using curl, follow these steps:
- Install the
ixudra/curlpackage. - Configure the installed package.
- Import the class into your controller file.
- Use
getandpostrequests throughcurl.
Install the ixudra/curl package
You can use a composer command to install ixudra/curl for your application, as shown below:
composer require ixudra/curl
Configure the installed package
Add the providers and the aliases to your app.php file. The app.php file should be present in the config directory.
'providers' => [
....
Ixudra\Curl\CurlServiceProvider::class,
],
'aliases' => [
....
'Curl' => Ixudra\Curl\Facades\Curl::class,
]
Import the class in your controller
To add the class to your controller, you need to include it in your controller file as shown below:
use Ixudra\Curl\Facades\Curl;
Usage
In the controller where you want to implement the curl, create a method
called getCurl().
Note: You can name the method whatever you like, but for this example
getCurl()is used.
Get request
Let’s perform a get() request using this package.
public function getCURL()
{
$response = Curl::to('https://jsonplaceholder.typicode.com/posts')
->get();
dd($response);
}
In the above code we use the Curl:: facade with the to() method to send a get request, after which the response is dumped.
In your case, instead of dumping the response, you may want to carry out the logic relevant to your application.
Post request
public function getCURL()
{
$response = Curl::to('https://example.com/posts')
->withData(['title'=>'Test', 'body'=>'sdsd', 'userId'=>1])
->post();
dd($response);
}
In the above code, the post request is made using the to() method, with withData specifying what data must be sent. Once again, the response is dumped.
Similarly, patch, put, and delete requests can be made in place of the put request in the code above.