Anshul Raj
Anshul Raj

Reputation: 71

Vue.js and Laravel passing json data

I have been working on building a simple table that gets its data from a mongodb database that is being queried for the json data and not the data needs to be passed to the vue component on the frontend but I am unable to understand how the json data is transferred from laravel to vue. To understand the code here is what I have done so far:

api.php route:

Route::middleware('api')->group(function () {
Route::resource('/home', [ProductController::class,'home']);
});

web.php route:

Route::get('/home', [PostController::class,'home']);

PostController Home method:

public function home() {
    $posts = Post::paginate(4);

    return response()->json($posts);
}

Home component:

<template>
<div>
        <table>
            <tr>
                <td>Id</td>
                <td>Title</td>
                <td>Status</td>
            </tr>
         <tr v-for="El in results" v-bind:key="El.id" >
             <td>{{El.id}}</td>
            <td>{{El.STATUS}}</td>
        </tr>
        </table>
        
</div>
</template>

<script>

export default{
     data() {
        return {
            results: []
        };
    },
    methods: {
        fetch() {
            axios.get('/api/home')
                .then(response => this.results = response.data)
                .catch(error => console.log(error));
        }
    }
}
</script>
Home.blade.php

@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row justify-content-center">
         
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Data</div>
                     
                <div class="card-body">
                  <home-component></home-component>
                </div>
                 
            </div>
        </div>
    </div>
</div>
@endsection 

All of this seems fine but when I run the code it just show the json and does not render any of the vue component. Any help is appreciated.

Upvotes: 1

Views: 1392

Answers (1)

Flame
Flame

Reputation: 7561

You are using the /home URL both as a data endpoint and an HTML endpoint. What you should do is design it something like this:

Route: GET /api/home
Returns: JSON data
Code: `return response()->json(...);`

Route:: GET /home
Returns: HTML data with javascript that requests /api/home
Code: `return view('home');`

Both routes are ordinary http requests, but one only serves JSON data and the other one serves HTML data to be interpreted by your browser.

Upvotes: 1

Related Questions