Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

allw's avatar
Level 4

Trying to loop out values in an array

Completely new at Vue.js and trying to follow laracasts' videos on vue.js but seem to have hit a snag. Below is my code for a component that is meant to fetch an array of students from a laravel backend, this seems to work as the console.log(this.students[i]) echoes out exactly what I would expect. However when I come to access those students using the li v-for it gives me a bullet point like there is an item but then does not output anything.

I have tried changing it to li v-for='student in this.students' and I have even tried nesting two loops in case somehow it was nested. Additionally if I just echo out {{ student }} I get a pair of curly braces signifying an empty json array.

<template>
   <div class="card-body">
     <li v-for='student in students'>
         {{ student.id }}
         {{ student.first_name }}
         {{ student.last_name }}
     </li>
   </div>
 </template>

<script>
  class Students {
    constructor() {
      this.students = {};
    }
  }
  export default {
    data: function() {
      return {
        students: new Students()
      }
    },
    mounted() {
      axios.get('/teacher/class/10X1')
        .then(response => {
          for (let i = 0; i < response.data.length; i++) {
            this.students[i] = response.data[i];
            console.log(this.students[i]);
          }
        })
        .catch(function (error) {
           console.log(error);
         });
    }
  }
</script>

Thanks for any input, I am sure it is something simple I am missing...

0 likes
4 replies
tykus's avatar
tykus
Best Answer
Level 104

Why is students an object; why not an array? What is the purpose of the Student class? Why not assign the response.data directly to this.students?

<script>
  export default {
    data: function() {
      return {
        students: []
      }
    },
    mounted() {
      axios.get('/teacher/class/10X1')
        .then(response => {
            this.students = response.data;
        })
        .catch(function (error) {
           console.log(error);
         });
    }
  }
</script>
1 like
allw's avatar
Level 4

Sorry thats a fragment of what I was doing earlier, but it hasn't changed the outcome

tykus's avatar

it hasn't changed the outcome

Did you try my suggested code above?

What is the structure of your JSON?

allw's avatar
Level 4

Oh you changed it...Yes it's working now, I swear I tried that earlier...thanks!

Please or to participate in this conversation.