Laravel’s ixudra package offers an effective method for making HTTP requests using curl.
Use curl to send get and post requests by performing the following actions:
- Install the package ixudra/curl.
- Adjust the installed package’s settings.
- In your controller code, import the class.
- Use curl to send get and post requests.
Install the ixudra/curl
package
Installing ixudra/curl for your application using a composer command is possible and is demonstrated below:
composer require ixudra/curl
Configure the installed package
Your app.php file should now include the providers and aliases. The config directory must contain the app.php file.
'providers' => [
....
Ixudra\Curl\CurlServiceProvider::class,
],
'aliases' => [
....
'Curl' => Ixudra\Curl\Facades\Curl::class,
]
Import the class in your controller
You must include the class in your controller file as shown below in order to add it to your controller:
use Ixudra\Curl\Facades\Curl;
Usage
Create a method called getCurl() in the controller where you wish to implement the curl .
Note: You can give the method whatever name you choose, but getCurl() is used in this example.
Get request
Let’s use this package to make a get() request.
public function getCURL()
{
$response = Curl::to('https://jsonplaceholder.typicode.com/posts')
->get();
dd($response);
}
The get request is sent in the code above using the Curl:: facade and the to() method, and the response is then dumped.
In your situation, you might wish to execute the logic necessary for your application rather than dumping the result.
Post request
public function getCURL()
{
$response = Curl::to('https://example.com/posts')
->withData(['title'=>'Test', 'body'=>'sdsd', 'userId'=>1])
->post();
dd($response);
}
The post request is made in the code above using the to() method, and the withData parameter specifies what data must be provided. The response is dropped once more.
The put request in the code above can be replaced with the patch, put, or delete requests.