[Vuejs]-AJAX Search with Laravel and Vue empty Results

0πŸ‘

βœ…

I GOT IT πŸ™‚

Controller:

public function search(Request $request)
{
    $files = DB::table('files')->where('name', 'like', '%' . $request->get('keywords') . '%')->get();
    return response()->json($files);
}

Route:

Route::get('/search', 'SearchController@search');

Vue:

<template>
<div>
    <input type="text" v-model="keywords">
    <ul v-if="results.length > 0">
        <li v-for="result in results" :key="result.id">{{ result.name }}</li>
    </ul>
</div>

</template>

<script>
    export default {
        data() {
            return {
                keywords: null,
                results: []
            };
        },

        watch: {
            keywords(after, before) {
                this.fetch();
            }
        },

        methods: {
            fetch() {
                axios.get('/search', { params: { keywords: this.keywords } })
                    .then(response => this.results = response.data)
                    .catch(error => {});
            }

        }
    }
    </script>

i edited the where function in my controller and i needed a β€œget” method , not a β€œpost” πŸ™‚

0πŸ‘

public function search(Request $request)
{
    $files = File::where('name', 'like', '%' . $request->get('keywords') . '%')->get();

    return response()->json($files);
}
<template>
<div>
    <input type="text" v-model="keywords">
    <ul v-if="results.length > 0">
        <li v-for="result in results" :key="result.id">{{ result.name }}</li>
    </ul>
</div>
</template>
<script>
export default {
    data() {
        return {
            keywords: null,
            results: []
        };
    },

    watch: {
        keywords(after, before) {
            this.fetch();
        }
    },

    methods: {
        fetch() {
            axios.post('/', { params: { keywords: this.keywords } })
                .then(response => this.results = response.data)
                .catch(error => {});
        }

    }
}
</script>

Leave a comment