Http Laravel code example

Example 1: larvel make http request

// To make requests, you may use the get, post, put, patch, and delete methods
// provided by the Http facade.

use Illuminate\Support\Facades\Http;

$response = Http::get('http://example.com');

// The get method returns an instance of Illuminate\Http\Client\Response,
// which provides a variety of methods that may be used to inspect the response:
$response->body() : string;
$response->json() : array|mixed;
$response->collect() : Illuminate\Support\Collection;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->failed() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;

Example 2: laravel send http post request json

use GuzzleHttp\Client;
class yourController extends Controller {

    public function saveApiData()
    {
        $client = new Client();
        $res = $client->request('POST', 'https://url_to_the_api', [
            'form_params' => [
                'client_id' => 'test_id',
                'secret' => 'test_secret',
            ]
        ]);
        echo $res->getStatusCode();
        // 200
        echo $res->getHeader('content-type');
        // 'application/json; charset=utf8'
        echo $res->getBody();
        // {"type":"User"...'
}

Example 3: use guzzle http client laravel

public function putGuzzleRequest()

{

    $client = new \GuzzleHttp\Client();

    $url = "http://myexample.com/api/posts/1";

    $myBody['name'] = "Demo";

    $request = $client->put($url,  ['body'=>$myBody]);

    $response = $request->send();



    dd($response);

}

Example 4: public function store(Request $request)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Store a new user.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $name = $request->input('name');

        //
    }
}

Example 5: laravel 6 make http request

$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', ['auth' =>  ['user', 'pass']]);
echo $res->getStatusCode(); // 200
echo $res->getBody(); // { "type": "User", ....

Example 6: laravel http client

composer require guzzlehttp/guzzle