1

How do I fetch data using vue js and laravel . I have created vue component and controller.

Here is my database table structure enter image description here

<script>
export default {

    data(){
        return {
            kudos : []
        }
    },
    created(){
        axios.get('./api/kudos')
        .then(response => this.kudos = response.data);
    }
}
</script>

What I need to do is fetch the database data to blade file using vuejs . Could someone guide me step by step?

  1. Controller
  2. Vue Component
  3. Blade File
1
  • Do you have any additional code to show? Commented Jun 4, 2019 at 10:44

2 Answers 2

1

I think you're looking for something like this?

Controller:

public function searchDatabase( Request $request )
{
    $foo = DB::table('bar')
        ->where([
            ["description", 'LIKE', "%{$request->input('query')}%"]
        ])
        ->limit(5)
        ->get();

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

YourComponent.vue

<template>
    <div id="wrapper">

        <div class="input-group">
            <input type="text" placeholder="Search database.." v-model="query" v-on:keyup="autoComplete" class="form-control">
        </div>

        <div class="panel-footer" v-if="results.length">
            <table class="table table-sm">
                <tr v-bind:key="result" v-for="result in results">
                    <td> {{ result.description }} </td>
                </tr>
            </table>
        </div>

    </div>
</template>

<script>
    export default{
        data(){
            return {
                query: '',
                url: '/search/blade/route',
                results: []
            }
        },
        methods: {
            autoComplete(){
                this.results = [];
                if(this.query.length > 2){
                    axios.get('/api/kudos', {params: {query: this.query}}).then(response => {
                        this.results = response.data;
                    });
                }
            }
        }
    }
</script>

search.blade.php

<your-component></your-component>
Sign up to request clarification or add additional context in comments.

2 Comments

Your searchDatabase function doesn't actually output anything.
Whoops! Good catch @ceejayoz . I just sterilized some existing code for this example and forgot to add that in.
0

Add the name of your data in your response

 <script>
   export default {

    data(){
        return {
            kudos : []
        }
    },
    created(){
        axios.get('./api/kudos')
        .then(response => this.kudos = response.data.NameOfYourData);
    }
  }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.