Showing associated table information in Vue.js

Currently, I am diving into the world of vuejs and harnessing the power of Laravel for the backend API. Within my project, I have set up tables named articles and articles_translations, where their relationships are defined in their respective models.

For the articles table, I went ahead and created a Vue component to handle its display:

<template>
    <div>
      <div v-for="article in articles" :key="article.articles">
        <h4>{{article.translations}}</h4>
      </div>
    </div>
</template>

<script>
import axios from 'axios'
import { mapGetters } from 'vuex'

    export default {
        layout: 'basic',

        computed: mapGetters({
          locale: 'lang/locale'
        }),
        data: function () {
            return {
                articles: []
            }
        },
        mounted() {
            var app = this;
            console.log(this.locale);
            axios.get('/api/articles')
                .then(response => {
                  // JSON responses are automatically parsed.
                  this.articles = response.data
                })
                .catch(e => {
                  this.errors.push(e)
                })
        }
    }
</script>

The data retrieved is displaying as expected: [ { "id": 1, "article_id": 1, "title": "This is an example title", "subtitle": "this is a subtitle", "content": "this is the content", "locale": "en", "created_at": null, "updated_at": null } ]

https://i.sstatic.net/WT6XV.png

My goal now is to format the article display in the following manner:

  1. article title article
  2. article subtitle
  3. article content

In Blade, I typically use {{ $article->article_translations->title }} to fetch related table data. How can I achieve this functionality in Vue? How do I format the data to meet the desired output?

Answer №1

If you want to include the article translation attributes in your code, you can do it like this:

<div v-for="article in articles" :key="article.articles">
    <div v-for="translation in article.translations">
        <h4>{{ translation.title }}</h4>
        {{ translation.subtitle }}
        {{ translation.content }}
    </div>
</div>

To display the translation attributes properly, make sure to add an additional loop since your translations are stored in an array.

Answer №2

Utilize the power of Laravel query builder along with inner join to solve your problem efficiently. Here is a quick example that will fetch a collection of properties or objects for you.

To explain further: The users table retrieves a User object, while the people table is related to the user through the user_id column. By joining these tables and selecting specific fields, you can achieve the desired result. See image here https://i.sstatic.net/7CBG0.png

$users = DB::table('people')
        ->join('users', 'users.id', '=' ,'people.user_id')
        ->select('users.*',
            'first_name',
            'last_name',
            'street_address',
            'city',
            'state',
            'contact_phone'
        )->get();

    return response()->json(['data' => $users], 200);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to determine if a sound is actively being played?

My current challenge involves implementing automated tests for the <audio> tag to ensure it is playing. For testing, I am utilizing the standard angular test suite with karma and protractor. "devDependencies": { "karma": "~0.10", "protracto ...

Loading remote content on a server for my Firefox OS application - On the Web and FxOS device

I haven't come across this issue in any forum, so I decided to reach out here. I'm encountering a problem with my FirefoxOS app on my FirefoxOS device (Geeksphone Developer Preview) when trying to retrieve remote content from the server. I am m ...

Tips for merging elements within a DataTable using php codeigniter

Let us delve into some LOGIC together. Column 1 Column 2 A one A one B two B two B one C three The outcome would appear as follows: Col ...

The jQuery Cookie is failing to be set with every click as expected

I am currently working on a layout switcher feature. When a user clicks on a specific div with the class name display, it triggers the toggling of another class called display-grid for visual enhancements. This functionality also involves switching classe ...

There was a problem accessing the website

Recently, I tried to access a web page from the server using command prompt by following a tutorial on YouTube. However, I encountered an error message while trying to open the page. The specific error is displayed below. Can someone please guide me on res ...

troubleshooting problems with feathers.JS using the npm start command

After developing two separate feathersJS applications, I encountered a situation where running npm start resulted in two unique types of errors for each app. How can I go about resolving this issue? View image here https://i.stack.imgur.com/RrsGW.pnghtt ...

Is there a way for me to address my update record query on the same page?

When I view the list of departments, clicking on details should display a pop-up with the specific department's details. However, it always shows the details of the last inserted record instead. Below is the code from my blade file: @extends('l ...

Exploring the Interaction Between Node.js and a Windows 10 Server on a Local Machine

I am curious about the interaction between Nodejs Server and a local machine. Specifically, I would like to understand how tasks such as: Thread Level CPU Cycle Socket Level IO Any help in clarifying this process would be greatly appreciated. ...

Error: Invariant Violation occurred with code 29 while using React Apollo and GraphQL

I encountered an error that says "Invariant Violation: 29." Could someone explain what this error means and if I missed something in my code that triggered it? The error occurred when I was trying to import the LocationSearch component into my index.js. im ...

When adding another Mesh, an error occurs in three.js stating: "Uncaught TypeError: Cannot read property 'center' of undefined - three.js:6754."

As I delve into coding with JS, I decided to experiment with Three.js. Everything was running smoothly until I included the line scene.add(my_square);. From that point on, my code failed to work and displayed the following error: Uncaught TypeError: Canno ...

Add a CSS class to a dropdown menu option in HTML and JavaScript (JQuery) if it has a specified ID

I am brand new to HTML and JQuery, and I'm struggling with setting a class for my select element when the currently selected option has an ID of "answer". This is crucial for checking the correctness of a multiple choice question. If achieving this i ...

After checking the checkbox to add a class, I then need to remove that class without having to interact with the entire document

When I click on a checkbox, an animation is added to a div. However, I am struggling to remove this animation unless I click elsewhere on the document. The goal is for the checkbox to both add and remove the class. JS $('#inOrder').click(functi ...

Ensure service is instantiated within an Angular 2 sub-module (a different approach from AngularJS run block)

Within a sub-module, there is a service that wraps a third-party module, instantiates it, and initializes its service for usage within the app. @Injectable() class SubmoduleInitializerService { constructor (thirdPartyService: ThirdPartyService) { ...

What is the best way to send FormData from a React JS axios post request to a Node server?

I am facing an issue where the form data is not reaching the node server even though it shows in the network payload at the time of request. Below are the snippets from different files involved in the process. let formData = new FormData(); // fo ...

Issue with jQuery's outerHeight() function persisting despite attempting to fix it with jQuery(window).load()

Once the content is loaded using AJAX, I need to retrieve the outerHeight of the loaded elements. Ajaxload file: $('#workshop').submit(function(event){ $.ajax({ url: URL, type: 'POST', data: $(' ...

Burger menu sidebar - Conceal on click outside

Is there a way to hide the left sidebar when a user clicks outside of it? Jsfiddle I attempted using the following code: $('.nav').click(function(event){ event.stopPropagation(); }); I also tried adding .stopPropagation(); to the body cli ...

What is the best way to transfer properties from one object to another in Angular?

Explore the code snippet provided below: const a={type:"apple"}; const b={type:"banana", color:"yellow"}; const c = Object.assign(a,b); //result: c={type:"banana", color:"yellow"} //desired outcome: {type:"banana"} What modifications can be made to reach ...

Switching from constructors to Hooks in REACT

I am currently working on adding a modal example within a function in my project. I have a specific requirement to incorporate hooks instead of using the constructor in a class-based component. This is the code snippet with the class-based implementation: ...

Having difficulty accessing and modifying child elements

I am encountering an issue where the 'remove' property is showing as undefined when I try to add or remove a class on an element. Upon inspecting the parent element using element.parentNode, I can see that there are child span elements present. H ...

Is there a way to trigger $q notify without initiating a $digest cycle?

Within my application, the $digest cycle typically takes around 5ms to complete. I heavily utilize $q.defer with deferred.notify throughout my codebase, but I've encountered an issue. Each time deferred.notify is triggered, it schedules a new digest c ...