Laravel 8 Tutorial - HTTP Client
In this video, we will learn about the HTTP Client in Laravel. The HTTP Client allows you to quickly make outgoing HTTP requests to communicate with other web applications. It makes it easy to send HTTP requests with data, headers, and trivial to integrate with web services.
Now, let's see how to make GET, POST, PUT, and DELETE requests using the HTTP Client. First, create a controller:
php artisan make:controller ClientController
Here, we will use JSONPlaceholder, a fake online REST API for testing. Switch to the browser and search for JSONPlaceholder. Click on the JSONPlaceholder link and let's use these routes.
Now, let's see the GET request first. Go to the ClientController and create a function:
public function getAllPost()
{
$response= Http::get('https://jsonplaceholder.typicode.com/posts');
return $response->json();
}
Also, import HTTP on top of the page:
use Illuminate\Support\Facades\Http;
Create a route for this:
Route::get('/posts',['ClientController::class, 'getAllPost']);
Now, let's check. Switch to the browser and type /posts. You can see all the posts here. Now, get an individual post by its ID:
public function PostById($id)
{
$post = Http::get('https://jsonplaceholder.typicode.com/posts/'.$id);
return $post;
}
Create a route:
Route::get('/post/{id}',[ClientController::class,'PostById']);
Now, let's check. Switch to the browser and type /posts/1. You can see the post here. If you change the post ID, let's say post ID is 4, you can see the post by its ID.
Now, make a POST request:
public function addPost()
{
$post = Http::post('https://jsonplaceholder.typicode.com/posts',[
'userId'=>1,
'title'=>'new post',
'body'=>'new post description'.
]);
return $post->json();
}
Create a route:
Route::get('/add-post',[ClientController::class, 'addPost');
Now, let's check. Switch to the browser and type /add-post. You can see a new post has been added.
Now, make a PUT request:
public function updatePost()
{
$response =Http::put('https://jsonplaceholder.typicode.com/posts/1',[
'title'=>'updated title',
'body'=>'updated description'.
]);
return $response->json();
}
Create a route:
Route::get('update-post',[ClientController::class,'updatePost');
Now, let's check. Switch to the browser and type /update-post. You can see the post has been updated.
Now, make a DELETE request:
public function deletePost($id)
{
$response = Http::delete('https://jsonplaceholder.typicode.com/posts'.$id);
return $response->json();
}
Create a route:
Route::get('/delete-post/{id}',[ClientController::class,'deletePost']);
Now, let's check. Switch to the browser and type /delete-post/2. You can see the post has been deleted.
In this way, you can use the HTTP Client in Laravel 8. That's all about the HTTP Client in Laravel 8.