the ability to develop a scalable, clear, and effective API. The resource controllers and Eloquent ORM in Laravel make it very easy to provide APIs and interact with your data models.
Setting Up Your Laravel Environment
First, ensure you have Composer installed on your machine. Then, create a new Laravel project by running:
composer create-project --prefer-dist laravel/laravel laravel-rest-api
After setting up your project, you might want to configure your environment settings in the .env
file, especially database settings.
Creating a Model, Migration, and Controller
Let’s build a basic API to handle ‘Books’. First, a model and a migration file will be created:
php artisan make:model Book -m
This command also creates a migration file for books
table. Edit the migration file in database/migrations
to include several fields:
Run migrations with:
php artisan migrate
Next, create a resource controller:
php artisan make:controller BookController --resource
There will be CRUD operation methods in this controller. Let’s now elaborate on a few of these techniques.
Implementing CRUD Operations
Activate the BookController.php file and incorporate the subsequent methods:
index
to retrieve all books
public function index()
{
$books = Book::all();
return response()->json($books);
}
2. Store
to add a new book
public function store(Request $request)
{
$book = Book::create($request->all());
return response()->json($book, 201);
}
3. show
to retrieve a single book
public function show(Book $book)
{
return response()->json($book);
}
4. update
to update a book
public function update(Request $request, Book $book)
{
$book->update($request->all());
return response()->json($book);
}
Routing
In your routes/api.php file, define routes for these API endpoints:
Route::apiResource('books', BookController::class);
Testing Your API
Now, you may use programmes like Postman or CURL to test your API. Here’s how to use CURL to test adding a new book:
curl -X POST -H "Content-Type: application/json" -d '{"title": "Laravel Unleashed", "author": "Taylor Otwell", "year": 2021}' http://localhost:8000/api/books