DEV Community

Mehedi Hasan
Mehedi Hasan

Posted on

How to Build a JSON API with Laravel and Vue.js

In this guide, we will walk through how to build a JSON API using Laravel as the backend and Vue.js as the frontend. By combining these two powerful technologies, we can create a modern, dynamic, and responsive web application. Laravel will handle the API logic, while Vue.js will manage the frontend interactions.

Prerequisites

Before we begin, make sure you have the following installed:

  • PHP (version 8.0 or above)
  • Composer (for Laravel)
  • Node.js (for Vue.js)
  • MySQL or any other database

Step 1: Install Laravel

To create a new Laravel project, use the following command:

composer create-project --prefer-dist laravel/laravel json-api
Enter fullscreen mode Exit fullscreen mode

This will install the latest version of Laravel in a directory named json-api. Navigate to your project folder:

cd json-api
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up the Database

Open the .env file and configure your database credentials:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=json_api
DB_USERNAME=root
DB_PASSWORD=your_password
Enter fullscreen mode Exit fullscreen mode

Next, create a new database named json_api in your MySQL or preferred database system.

Step 3: Create a Model and Migration

We will now create a Post model and its corresponding migration for our API. Run the following Artisan command:

php artisan make:model Post -m
Enter fullscreen mode Exit fullscreen mode

This will create a Post model in the app/Models directory and a migration file in the database/migrations directory.

Now, open the migration file and define the table structure:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}
Enter fullscreen mode Exit fullscreen mode

Run the migration to create the posts table in the database:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 4: Create API Routes

To define the routes for your API, open routes/api.php and add the following routes:

use App\Http\Controllers\PostController;

Route::apiResource('posts', PostController::class);
Enter fullscreen mode Exit fullscreen mode

This will generate RESTful routes for index, store, show, update, and destroy actions.

Step 5: Create a Controller

Now, create a controller that will handle the API requests for the Post model:

php artisan make:controller PostController --api
Enter fullscreen mode Exit fullscreen mode

Open PostController.php in the app/Http/Controllers directory and implement the CRUD operations:

1. index() – Retrieve All Posts

public function index()
{
    $posts = Post::all();
    return response()->json($posts);
}
Enter fullscreen mode Exit fullscreen mode

2. store() – Create a New Post

public function store(Request $request)
{
    $request->validate([
        'title' => 'required|string|max:255',
        'content' => 'required|string',
    ]);

    $post = Post::create($request->all());

    return response()->json($post, 201);
}
Enter fullscreen mode Exit fullscreen mode

3. show() – Retrieve a Single Post

public function show($id)
{
    $post = Post::findOrFail($id);
    return response()->json($post);
}
Enter fullscreen mode Exit fullscreen mode

4. update() – Update a Post

public function update(Request $request, $id)
{
    $post = Post::findOrFail($id);
    $post->update($request->all());

    return response()->json($post);
}
Enter fullscreen mode Exit fullscreen mode

5. destroy() – Delete a Post

public function destroy($id)
{
    $post = Post::findOrFail($id);
    $post->delete();

    return response()->json(null, 204);
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Enable CORS

To allow Vue.js to communicate with your Laravel API, you need to enable CORS (Cross-Origin Resource Sharing). Install the Laravel CORS package by running:

composer require fruitcake/laravel-cors
Enter fullscreen mode Exit fullscreen mode

Now, publish the configuration file by running:

php artisan vendor:publish --tag="cors"
Enter fullscreen mode Exit fullscreen mode

In the config/cors.php file, you can adjust the settings. By default, the following should work:

'paths' => ['api/*'],
Enter fullscreen mode Exit fullscreen mode

Step 7: Install Vue.js

Now, let's set up the Vue.js frontend. First, install the frontend dependencies:

npm install
Enter fullscreen mode Exit fullscreen mode

Next, create a new Vue component that will interact with the Laravel API. Inside the resources/js/components directory, create a file called PostList.vue:

<template>
  <div>
    <h1>Posts</h1>
    <ul>
      <li v-for="post in posts" :key="post.id">{{ post.title }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      posts: []
    }
  },
  created() {
    this.fetchPosts()
  },
  methods: {
    async fetchPosts() {
      try {
        const response = await fetch('/api/posts')
        this.posts = await response.json()
      } catch (error) {
        console.error(error)
      }
    }
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

Step 8: Update app.js

Open resources/js/app.js and register the PostList component:

import Vue from 'vue'
import PostList from './components/PostList.vue'

new Vue({
  el: '#app',
  components: {
    PostList
  }
})
Enter fullscreen mode Exit fullscreen mode

Step 9: Update Blade File

In the resources/views/welcome.blade.php file, replace its content with the following to load Vue.js:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue.js with Laravel</title>
</head>
<body>
    <div id="app">
        <post-list></post-list>
    </div>

    <script src="{{ mix('js/app.js') }}"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 10: Build the Assets

Run the following command to compile the Vue components:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Step 11: Serve Your Application

Finally, start the Laravel development server:

php artisan serve
Enter fullscreen mode Exit fullscreen mode

Now, when you navigate to http://localhost:8000, you should see the Vue.js component displaying the list of posts retrieved from the Laravel API.

Conclusion

Congratulations! You've successfully built a JSON API with Laravel and Vue.js. Laravel handles the backend logic and database operations, while Vue.js provides a dynamic and interactive frontend. This stack is highly scalable and can be extended to handle complex business logic and sophisticated user interfaces.

From here, you can explore adding features like authentication, pagination, or filtering data, making your application even more robust and feature-rich.

Top comments (0)