Search code examples
jsonlaravelvue.jscontrollerv-for

Laravel Vue displaying from database table result using v-for directive not correctly


I have a problem with laravel and vue about displaying the result from database table find method. What I don't quite understand is why the v-for directive parsing the json result incorrectly.

Here is the Vue code :

<template>
    <table class="table table-hover">
        <thead>
        <tr>
            <th>Class</th>
            <th>Amount of Students</th>
            <th>Teacher</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="classroom in classrooms" :key="classroom.id">
            <td>{{ classroom.class_no }}&bull;{{ classroom.field }}&bull;{{ classroom.room_no }}</td>
            <td>{{ classroom.amount_students }}</td>
            <td>{{ classroom.teacher }}</td>
            <td>
                <a href="#">
                    <i class="fa fa-edit blue"></i>
                </a>
            </td>
        </tr>
        </tbody>
    </table>
</template>

<script>
export default {
    data () {
        return {
            classrooms : {
                "success": true,
                "data": { "id": 1, "class_no": 1, "field": "Architecture", "room_no": 4, "amount_students": 40, "teacher": "Bobby Fisher" },
                "message": "Find Classroom Detail"
            }
        }
    }
}
</script>

The json classrooms itself is actually the result from the controller :

    public function show($level)
    {
        $classrooms = ClassRoom::where('class_no', $level)->firstOrFail();

        return $this->sendResponse($classrooms , 'Find Classroom Detail');
    }

And here is screenshot of the wrong result :

The result should be only a single row

Please help me to solve this problem.


Solution

  • Actually, as you are iterating over the classrooms which is an object having three keys, so the for loop is iterating over each key once.

    If you only want to iterate over the data key then just return the data from the backend.

    You can use a v-if condition to check whether the current key contains a class_no and if yes then display the row otherwise not.

    <tr v-for="classroom in classrooms" :key="classroom.id" v-if="classroom.class_no">
        <td>{{ classroom.class_no }}&bull;{{ classroom.field }}&bull;{{ classroom.room_no }}</td>
        <td>{{ classroom.amount_students }}</td>
        <td>{{ classroom.teacher }}</td>
        <td>
            <a href="#">
                <i class="fa fa-edit blue"></i>
            </a>
        </td>
    </tr>