Building crud operations with Laravel and Nuxt

Step 1: Set up Laravel Backend API

  1. Install Laravel 10 by running the following command in your terminal:
  2. composer create-project --prefer-dist laravel/laravel backend
  3. Create a database and update the database connection details in the .env file.
  4. Generate a model and migration for your resource (e.g., Article) by running the following command:
  5. php artisan make:model Article --migration
  6. In the generated migration file (e.g., database/migrations/{timestamp}_create_articles_table.php), define the table schema for your resource. For example, you can add a title and body field:
  7. <?php
      public function up()
      {
        Schema::create('articles', function (Blueprint $table) {
          $table->id();
          $table->string('title');
          $table->text('body');
          $table->timestamps();
        });
      }
      
  8. Run the migration to create the articles table in your database:
  9. php artisan migrate
  10. Create a controller for your resource (e.g., ArticleController) by running the following command:
  11. php artisan make:controller ArticleController --resource
  12. In the generated controller file (e.g., app/Http/Controllers/ArticleController.php), implement the CRUD operations. Here’s an example implementation:
  13. <?php
      namespace App\Http\Controllers;
    
      use App\Models\Article;
      use Illuminate\Http\Request;
    
      class ArticleController extends Controller
      {
        public function index()
        {
          return Article::all();
        }
    
        public function store(Request $request)
        {
          $article = Article::create($request->all());
          return response()->json($article, 201);
        }
    
        public function show(Article $article)
        {
          return $article;
        }
    
        public function update(Request $request, Article $article)
        {
          $article->update($request->all());
          return response()->json($article, 200);
        }
    
        public function destroy(Article $article)
        {
          $article->delete();
          return response()->json(null, 204);
        }
      }
      
  14. Define the API routes for your resource in the routes/api.php file. Here’s an example:
  15. <?php
      use App\Http\Controllers\ArticleController;
    
      Route::apiResource('articles', ArticleController::class);
      
  16. Start the Laravel development server by running the following command:
  17. php artisan serve

Step 2: Set up Nuxt.js Frontend

  1. Install Nuxt.js by running the following command in your terminal:
  2. npx create-nuxt-app frontend

    Follow the prompts to set up your Nuxt.js project.

  3. In the generated Nuxt.js project, open the nuxt.config.js file and update the proxy configuration to point to your Laravel API:
  4. export default {
        // ...
        axios: {
          proxy: true,
        },
        proxy: {
          '/api/': 'http://localhost:8000',
        },
        // ...
      }
      

Step 3: Create a Vue component to display and manage the CRUD operations for your resource (e.g., ArticleList.vue):

<template>
    <div>
        <h1>Articles</h1>
        <ul>
            <li v-for="article in articles" :key="article.id">
                {{ article.title }}
                <button @click="editArticle(article)">Edit</button>
                <button @click="deleteArticle(article)">Delete</button>
            </li>
        </ul>

        <h2 v-if="selectedArticle">Edit Article</h2>
        <form v-if="selectedArticle" @submit.prevent="saveArticle">
            <input v-model="selectedArticle.title" type="text" placeholder="Title" />
            <textarea v-model="selectedArticle.body" placeholder="Body"></textarea>
            <button type="submit">Save</button>
        </form>

        <h2 v-else>Create Article</h2>
        <form v-else @submit.prevent="createArticle">
            <input v-model="newArticle.title" type="text" placeholder="Title" />
            <textarea v-model="newArticle.body" placeholder="Body"></textarea>
            <button type="submit">Create</button>
        </form>
    </div>
</template>

<script>
export default {
    data() {
        return {
            articles: [],
            newArticle: {
                title: '',
                body: '',
            },
            selectedArticle: null,
        };
    },

    async created() {
        await this.fetchArticles();
    },

    methods: {
        async fetchArticles() {
            const response = await this.$axios.get('/api/articles');
            this.articles = response.data;
        },

        async createArticle() {
            const response = await this.$axios.post('/api/articles', this.newArticle);
            this.articles.push(response.data);
            this.newArticle = { title: '', body: '' };
        },

        async editArticle(article) {
            this.selectedArticle = { ...article };
        },

        async saveArticle() {
            await this.$axios.put(`/api/articles/${this.selectedArticle.id}`, this.selectedArticle);
            this.selectedArticle = null;
            await this.fetchArticles();
        },

        async deleteArticle(article) {
            await this.$axios.delete(`/api/articles/${article.id}`);
            this.articles = this.articles.filter(a => a.id !== article.id);
        },
    },
};
</script>

Step 4: Update the pages/index.vue file to use the ArticleList component:

<template>
    <div>
        <ArticleList />
    </div>
</template>

<script>
import ArticleList from '~/components/ArticleList.vue';

export default {
    components: {
        ArticleList,
    },
};
</script>

Step 5: Start the Nuxt.js development server by running the following command:

npm run dev

Your Nuxt.js frontend is now ready to consume the Laravel backend API and perform CRUD operations on the Article resource.

That’s it! You now have a demo CRUD application with Laravel 10 and Nuxt.js. You can access the frontend application at http://localhost:3000.

Leave A Comment