In this tutorial, we’ll create a Laravel application that interacts with an external API to fetch and display a paginated list of posts. We’ll also implement buttons that trigger delete and update calls to the external API. Calling external APIs allow us to integrate with any third parties that exposes their functionality accordingly.
Controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class PostController extends Controller
{
public function index()
{
$response = Http::get('https://jsonplaceholder.typicode.com/posts');
$posts = $response->json();
return view('posts.index', ['posts' => $posts]);
}
public function edit($id)
{
$response = Http::get('https://jsonplaceholder.typicode.com/posts/' . $id);
$post = $response->json();
return view('posts.edit', ['post' => $post]);
}
public function update(Request $request, $id)
{
// Simulates update logic for a real application (not supported by this API)
$response = Http::put('https://jsonplaceholder.typicode.com/posts/' . $id, [
'title' => $request->input('title'),
'body' => $request->input('body'),
]);
// Simulated response for successful or failed update
if ($response->successful()) {
return redirect()->route('posts.index')->with('success', 'Post updated successfully!');
} else {
return redirect()->route('posts.index')->with('error', 'Failed to update post. Please try again.');
}
}
public function destroy($id)
{
// Simulates deletion logic for a real application (not supported by this API)
$response = Http::delete('https://jsonplaceholder.typicode.com/posts/' . $id);
// Simulated response for successful or failed deletion
if ($response->successful()) {
return redirect()->route('posts.index')->with('success', 'Post deleted successfully!');
} else {
return redirect()->route('posts.index')->with('error', 'Failed to delete post. Please try again.');
}
}
}
web.php
use App\Http\Controllers\PostController;
Route::get('/', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/{id}/edit', [PostController::class, 'edit'])->name('posts.edit');
Route::put('/posts/{id}', [PostController::class, 'update'])->name('posts.update');
Route::delete('/posts/{id}', [PostController::class, 'destroy'])->name('posts.destroy');
view.php
@section('content')
<div class="container mt-4">
<h1>Posts</h1>
<div class="table-responsive mt-3">
<table class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>Body</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach($posts as $post)
<tr>
<td>{{ $post['title'] }}</td>
<td>{{ $post['body'] }}</td>
<td>
<div class="d-flex">
<a href="{{ route('posts.edit', $post['id']) }}" class="btn btn-sm btn-primary me-2">
<i class="bi bi-pencil"></i>
</a>
<form action="{{ route('posts.destroy', $post['id']) }}" method="POST">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-sm btn-danger">
<i class="bi bi-trash"></i>
</button>
</form>
</div>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>