Backend DevelopmentFrontend Development

Building a Book Selling Website with Laravel and Nuxt.js 3

Building a Book Selling Website with Laravel and Nuxt 3

In this four-part tutorial series, we will build a simple online bookstore using Laravel and Nuxt.js 3.

 

 

 

 

In the project we will demonstrate how to build a modern e-commerce application by separating the backend and frontend responsibilities:

  • Laravel: Handles the database, business logic, API endpoints, and data validation.
  • Nuxt 3: Handles the storefront, user interface, navigation, and rendering of book information.

We will build the application incrementally, starting with the book catalog, then adding shopping cart and checkout functionality, and finally building a simple administration dashboard.

 

Understanding the project architecture

let’s understand how our application components communicate.

We will use a decoupled architecture, meaning Laravel and Nuxt will be two separate applications.

This separation allows us to develop and deploy the frontend and backend independently.

project structure

We will create two separate directories:

bookstore/
│
├── bookstore-api/ # Laravel backend
│
└── bookstore-frontend/ # Nuxt 3 frontend

For local development each project will run using it’s own port:

  • Laravel API: http://localhost:8000
  • Nuxt frontend: http://localhost:3000

 

Creating the laravel project

First, let’s create our laravel backend.

Inside of the bookstore/ directory open a cmd and run:

composer create-project laravel/laravel bookstore-api

Navigate into the project:

cd bookstore-api

Start the laravel development server:

php artisan serve

Laravel should now be available on:

http://localhost:8000

 

Creating the Nuxt3 project

Now let’s create our frontend application.

From the parent bookstore directory:

npx nuxi@latest init bookstore-frontend

You will be asked to select a template to start with, so select the minimal starter with single App.vue.

The next step you will be asked to select the package manager (npm, pnpm, yarn, etc). In my case i selected npm and proceed. 

Wait a few minutes until npm installing dependencies.

Start the development server:

npm run dev

Nuxt should be available at:

http://localhost:3000

 

Configure the Laravel API URL:

Create or update the .env file in the Nuxt project:

NUXT_PUBLIC_API_BASE=http://localhost:8000/api

Then configure nuxt.config.ts:

The public runtime configuration will read NUXT_PUBLIC_API_BASE automatically.

We will use this configuration throughout the application rather than hardcoding the API URL in individual components.

 

Configure the database:

Create a Mysql database:

CREATE DATABASE bookstore;

Open the .env file and configure the database connection:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=bookstore
DB_USERNAME=<db user>
DB_PASSWORD=<db password>

Run the default migrations:

php artisan migrate

 

Install Laravel API support:

For recent laravel versions, API routing and sanctum can be installed using:

php artisan install:api

This prepares the API routing infrastructure and installs Sanctum for the authentication functionality we will be doing later.

You will find the new routes file inside of routes/api.php

 

Designing the database:

Before implementing the catalog, let’s design the database structure.

We will need these tables:

categories:

id
name
slug
timestamps

books: Store book information

id
category_id
title
slug
description
author
price
stock
cover_image
timestamps

users: Stores customer information, laravel provides this table by default.

A category can contain multiple books, while each book belongs to one category.

We will keep the author as a regular text field. 

 

Create the category migration:

php artisan make:model Category -m

This creates the model and migration together.

Open the migration file:

database/migrations/xxxx_create_categories_table.php

public function up(): void
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('slug')->unique();
        $table->timestamps();
    });
}

Create the book migration:

php artisan make:model Book -m

Open the migration file:

database/migrations/xxxx_create_books_table.php

public function up(): void
{
    Schema::create('books', function (Blueprint $table) {
        $table->id();

        $table->foreignId('category_id')
            ->constrained()
            ->cascadeOnDelete();

        $table->string('title');
        $table->string('slug')->unique();
        $table->text('description')->nullable();
        $table->string('author');
        $table->decimal('price', 10, 2);
        $table->unsignedInteger('stock')->default(0);
        $table->string('cover_image')->nullable();

        $table->timestamps();
    });
}

The stock field will help us determine whether a book is available for purchase. And the price field defined as decimal because prices should be stored as fixed decimal percision.

 

Run migrations:

php artisan migrate

Our initial database structure is now ready.

 

Creating Eloquent models and relationships:

Let’s implement the relationships between categories and books.

Category model:

app/Models/Category.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

#[Fillable('name', 'slug')]
class Category extends Model
{
    public function books() : HasMany
    {
        return $this->hasMany(Book::class);
    }
}

I added the fillables using PHP 8 attribute syntax:

#[Fillable('name', 'slug')]

Instead of this you can also using the normal way by declaring the protected $fillable property like so:

protected $fillable = [
        'name',
        'slug',
    ];

The books() relationship allows us to retrieve all books belonging to a particular category.

 

Book model:

app/Models/Book.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

#[Fillable('category_id', 'title', 'slug', 'description', 'author', 'price', 'stock', 'cover_image')]
class Book extends Model
{
    protected function casts(): array
    {
        return [
            'price' => 'decimal:2',
            'stock' => 'integer',
        ];
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }
}

Now we can retrieve the category associated with a book:

$book = Book::with('category')->find(1);

echo $book->category->name;

 

Adding sample data using seeders

Let’s add some sample books and categories, create the seeders below:

php artisan make:seeder CategorySeeder

php artisan make:seeder BookSeeder

Open database/seeders/CategorySeeder.php:

<?php

namespace Database\Seeders;

use App\Models\Category;
use Illuminate\Database\Seeder;

class CategorySeeder extends Seeder
{
    public function run(): void
    {
        $categories = [
            ['name' => 'Programming', 'slug' => 'programming'],
            ['name' => 'Business', 'slug' => 'business'],
            ['name' => 'Science', 'slug' => 'science'],
            ['name' => 'Self Development', 'slug' => 'self-development'],
        ];

        foreach ($categories as $category) {
            Category::updateOrCreate(
                ['slug' => $category['slug']],
                $category
            );
        }
    }
}

Then open database/seeders/BookSeeder.php:

<?php

namespace Database\Seeders;

use App\Models\Book;
use App\Models\Category;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class BookSeeder extends Seeder
{
    public function run(): void
    {
        $books = [
            [
                'title' => 'Clean Code',
                'author' => 'Robert C. Martin',
                'category' => 'programming',
                'price' => 35.00,
                'stock' => 10,
                'description' => 'A handbook of agile software craftsmanship.',
            ],
            [
                'title' => 'The Pragmatic Programmer',
                'author' => 'David Thomas',
                'category' => 'programming',
                'price' => 40.00,
                'stock' => 8,
                'description' => 'Practical advice for becoming a better programmer.',
            ],
            [
                'title' => 'Rich Dad Poor Dad',
                'author' => 'Robert Kiyosaki',
                'category' => 'business',
                'price' => 25.00,
                'stock' => 15,
                'description' => 'A book about financial education and investing.',
            ],
            [
                'title' => 'Atomic Habits',
                'author' => 'James Clear',
                'category' => 'self-development',
                'price' => 30.00,
                'stock' => 12,
                'description' => 'A guide to building good habits.',
            ],
        ];

        foreach ($books as $book) {
            $category = Category::where(
                'slug',
                $book['category']
            )->firstOrFail();

            Book::updateOrCreate(
                ['slug' => Str::slug($book['title'])],
                [
                    'category_id' => $category->id,
                    'title' => $book['title'],
                    'slug' => Str::slug($book['title']),
                    'author' => $book['author'],
                    'price' => $book['price'],
                    'stock' => $book['stock'],
                    'description' => $book['description'],
                ]
            );
        }
    }
}

Register the seeders by opening database/seeders/DatabaseSeeder.php

public function run(): void
{
    $this->call([
        CategorySeeder::class,
        BookSeeder::class,
    ]);
}

Next run:

php artisan db:seed

We now have some categories and books data in the database.

 

Building the Laravel REST API

Now that our database and models are ready, let’s expose the catalog through REST API endpoints.

Initially we will need these endpoints:

Method Endpoint  
GET /api/books Retrieve books
GET /api/books/{slug} Retrieve book details
Get /api/categories Retrieve categories

 

Create API Resources

Rather than returning Eloquent models directly, Laravel API Resources allow us to control the JSON structure returned to Nuxt.

 

Create a Book Resource:

php artisan make:resource BookResource

Open app/Http/Resources/BookResource.php:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class BookResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'author' => $this->author,
            'description' => $this->description,
            'price' => $this->price,
            'stock' => $this->stock,
            'cover_image' => $this->cover_image,

            'category' => [
                'id' => $this->category?->id,
                'name' => $this->category?->name,
                'slug' => $this->category?->slug,
            ],

            'created_at' => $this->created_at,
        ];
    }
}

Create a Category Resource:

php artisan make:resource CategoryResource

Open app/Http/Resources/CategoryResource.php:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class CategoryResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'slug' => $this->slug,
        ];
    }
}

 

Create the Book Api Controller:

Run:

php artisan make:controller Api/BookController

Open app/Http/Controllers/Api/BookController.php:

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\BookResource;
use App\Models\Book;
use Illuminate\Http\Request;

class BookController extends Controller
{

    public function index(Request $request)
    {
        $query = Book::with('category');

        $query->when($request->search, function ($query, $search) {
            $query->where('title', 'like', "%{$search}%")
                ->orWhere('author', 'like', "%{$search}%");
        });

        $query->when($request->category, function ($query, $category) {
            $query->whereHas('category', function ($q) use ($category) {
                $q->where('slug', $category);
            });
        });

        $books = $query
            ->latest()
            ->paginate(12)
            ->withQueryString();

        return BookResource::collection($books);
    }

    public function show(string $slug)
    {
        $book = Book::with('category')
            ->where('slug', $slug)
            ->firstOrFail();

        return new BookResource($book);
    }
}

The index() method retrieves the books from the database. This method typically will be used from a search books page. Supports searching by title or author and also filtering by particular category. The data is retrieved by latest data and paginated to 12 items.

The show() method retrieves an individual book using its slug instead of its database ID.

For example:

GET /api/books/clean-code

Using slugs gives us more readable URLs when we build the book details pages in Nuxt.

 

Create the Category Api Controller:

php artisan make:controller Api/CategoryController

Open app/Http/Controllers/Api/CategoryController.php:

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\CategoryResource;
use App\Models\Category;

class CategoryController extends Controller
{
    public function index()
    {
        $categories = Category::orderBy('name')->get();

        return CategoryResource::collection($categories);
    }
}

 

Register api routes

Open routes/api.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\BookController;
use App\Http\Controllers\Api\CategoryController;


Route::controller(BookController::class)->group(function () {
    Route::get('/books', 'index');
    Route::get('/books/{slug}', 'show');
});

Route::controller(CategoryController::class)->group(function () {
   Route::get('/categories', 'index');
});

 

Testing the api

Start the laravel server:

php artisan serve

Next using an HTTP client like postman you can test the endpoints.

For example:

http://localhost:8000/api/books

A successful response should look like this:

{
    "data": [
        {
            "id": 1,
            "title": "Clean Code",
            "slug": "clean-code",
            "author": "Robert C. Martin",
            "description": "A handbook of agile software craftsmanship.",
            "price": "35.00",
            "stock": 10,
            "cover_image": null,
            "category": {
                "id": 1,
                "name": "Programming",
                "slug": "programming"
            },
            "created_at": "2026-11-05T..."
        }
    ],
    "links": {},
    "meta": {}
}

Configuring Laravel Cors

This is an essential step when exposing Laravel Api’s with an external project. 

Our Nuxt application runs on port 3000, while Laravel runs on port 8000. These are different origins, so the browser needs permission to make cross-origin API requests.

Publish the config/cors.php

php artisan config:publish cors

Configure it as follows:

<?php

return [

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['http://localhost:3000',],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];

For now, we are allowing our local Nuxt application to communicate with Laravel.

In production, replace the local origin with your actual frontend domain.

The credentials setting will also be useful when we configure Sanctum authentication.

 

Clear configuration cache:

php artisan config:clear

 

Continue to part 2: Connecting Nuxt 3 with Laravel

0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted