Creating RESTful APIs with Laravel 11 is straightforward and powerful. Laravel provides a simple and elegant way to build APIs quickly. In this tutorial, we’ll create a simple RESTful API for managing a collection of books.
Step 1: Setting Up Laravel
First, make sure you have Laravel installed. If not, you can install it via Composer:
composer create-project --prefer-dist laravel/laravel book-api
Step 2: Database Configuration
Let’s set up a database. Create a database named book_api
and configure your .env
file accordingly:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=book_api
DB_USERNAME=root
DB_PASSWORD=
Step 3: Create a Model and Migration
We’ll create a Book
model and its corresponding migration to store our books.
php artisan make:model Book -m
In the migration file, define the schema for the books
table:
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('author');
$table->timestamps();
});
}
Run the migration to create the books
table:
php artisan migrate
Step 4: Create a Controller
Generate a controller named BookController
:
php artisan make:controller BookController --api
Step 5: Define Routes
Define routes in routes/api.php
:
use App\Http\Controllers\BookController;
Route::apiResource('/books', BookController::class);
Step 6: Implement Controller Methods
In BookController.php
, implement the CRUD methods:
use App\Models\Book;
use Illuminate\Http\Request;
public function index()
{
return Book::all();
}
public function store(Request $request)
{
return Book::create($request->all());
}
public function show(Book $book)
{
return $book;
}
public function update(Request $request, Book $book)
{
$book->update($request->all());
return $book;
}
public function destroy(Book $book)
{
$book->delete();
return response()->json(null, 204);
}
Step 7: Testing
You can now test your API using tools like Postman or curl.
Example requests:
- GET
/api/books
– Retrieve all books - GET
/api/books/{id}
– Retrieve a specific book - POST
/api/books
– Create a new book - PUT
/api/books/{id}
– Update a book - DELETE
/api/books/{id}
– Delete a book
Conclusion
In this tutorial, we created a simple RESTful API for managing a collection of books using Laravel 11. This is just the beginning; Laravel provides a rich set of features to further develop and secure your APIs. Happy coding!