Laravel How to convey Request

Laravel: learn to pass request w/example. See how to use request() & $request variables to access & modify request data.

Making an HTTP Request with Laravel

Laravel provides several different ways to make HTTP requests. You can use the HTTP facade to send requests to a given URL. The request will be sent using the specified HTTP verb (e.g. GET, POST, PUT, etc.) and the specified request body.

The most basic example of using the HTTP facade is to send a GET request:


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

To send a POST request, you can use the 'post' method:


$response = IlluminateSupportFacadesHttp::post('http://example.com', [
    'name' => 'John',
    'age'  => 25
]);

You can also include a body with your request:


$response = IlluminateSupportFacadesHttp::post('http://example.com', [
    'name' => 'John',
    'age'  => 25
], [
    'Content-Type' => 'application/json'
]);

If you need to send a PUT or DELETE request, you can use the 'put' and 'delete' methods. They both take the same arguments as the 'post' method:


$response = IlluminateSupportFacadesHttp::put('http://example.com', [
    'name' => 'John',
    'age'  => 25
], [
    'Content-Type' => 'application/json'
]);

$response = IlluminateSupportFacadesHttp::delete('http://example.com', [
    'name' => 'John',
    'age'  => 25
], [
    'Content-Type' => 'application/json'
]);

You can also make more complex requests, such as sending a PATCH request:


$response = IlluminateSupportFacadesHttp::patch('http://example.com', [
    'name' => 'John',
    'age'  => 25
], [
    'Content-Type' => 'application/json'
]);

You can also send requests with other HTTP verbs, such as HEAD or OPTIONS:


$response = IlluminateSupportFacadesHttp::head('http://example.com');

$response = IlluminateSupportFacadesHttp::options('http://example.com');

The HTTP facade also makes it easy to send requests with custom headers:


$response = IlluminateSupportFacadesHttp::get('http://example.com', [
    'headers' => [
        'X-My-Header' => 'John'
    ]
]);

Finally, if you need to send a request with a custom request body, you can do so by passing a string as the third argument:


$response = IlluminateSupportFacadesHttp::post('http://example.com', [
    'name' => 'John',
    'age'  => 25
], 'This is the custom request body');

Using the HTTP facade in Laravel makes it easy to send HTTP requests with a variety of verb, headers, and request body options.

Answers (0)