This tutorial aims to introduce you to the process of building RESTful APIs using Laravel. By the end of this tutorial, you will have built your own API and understand the fundamentals of Laravel API development.
You'll get hands-on experience:
First, let's create a new Laravel project. Open your terminal and type:
composer create-project --prefer-dist laravel/laravel blog
This will create a new Laravel project named blog
.
Routes in Laravel are defined in the routes/api.php
file. Let's define a route for retrieving blog posts:
Route::get('/posts', 'PostController@index');
This means when we make a GET request to /posts
, Laravel will execute the index
method of PostController
.
Now, let's generate the PostController
:
php artisan make:controller PostController --api
This command creates a controller with methods for each API verb (index, show, store, update, delete).
Let's add logic to our controller for CRUD operations. We'll use Eloquent ORM, Laravel's built-in ORM.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostController extends Controller
{
// Show all posts
public function index()
{
return Post::all();
}
// Store a new post
public function store(Request $request)
{
return Post::create($request->all());
}
// Show a single post
public function show(Post $post)
{
return $post;
}
// Update a post
public function update(Request $request, Post $post)
{
$post->update($request->all());
return $post;
}
// Delete a post
public function destroy(Post $post)
{
$post->delete();
return response()->json(null, 204);
}
}
Each method corresponds to a CRUD operation and handles HTTP requests accordingly.
In this tutorial, you learned how to set up a Laravel project, define routes, create controllers, and implement CRUD operations. You are now able to build a RESTful API using Laravel.
Create a new Laravel project and define routes for a resource other than Post
. Generate a corresponding controller.
In the controller you just created, implement the index
and show
methods to return all instances of your resource and a single instance, respectively.
Complete the CRUD operations by adding store
, update
, and destroy
methods to your controller.
For further practice, consider adding validation to your API endpoints, or adding additional functionality such as filtering or sorting.
Remember: The best way to learn is by doing. Happy coding!