Laravel makes it incredibly easy to build RESTful APIs. In this guide, we'll create a simple API for managing blog posts.
Defining the Route
Route::apiResource('posts', PostController::class);
The Controller
class PostController extends Controller
{
public function index()
{
return PostResource::collection(
Post::latest()->paginate()
);
}
public function store(StorePostRequest $request)
{
$post = Post::create($request->validated());
return new PostResource($post);
}
}
Adding Filters
Use query parameters to filter results:
Post::where('category_id', $request->category_id)
->latest()
->paginate();
Laravel handles pagination, authentication, and rate limiting out of the box.