My goal is to create a search feature using AJAX and Vue.
I have a model named "file" which contains all my files.
Next, I created a controller called searchcontroller.php
public function search(Request $request)
{
$files = File::where('name', $request=>keywords)->get();
return response()->json($files);
}
This is the route for my search functionality
Route::post('/', 'SearchController@search');
Additionally, I have a search.vue file:
<template>
<div>
<input type="text" v-model="keywords">
<ul v-if="results.length > 0">
<li v-for="result in results" :key="result.id" v-text="result.name"></li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
keywords: null,
results: []
};
},
watch: {
keywords(after, before) {
this.fetch();
}
},
methods: {
fetch() {
axios.get('/', { params: { keywords: this.keywords } })
.then(response => this.results = response.data)
.catch(error => {});
}
}
}
</script>
When I type a letter, the response seems to work but it displays an excessive amount of empty list items.
You can see the issue here: https://i.sstatic.net/tsuN8.png
I would like to implement the solution shown in this example: https://jsfiddle.net/hej7L1jy/2/
Upon console logging the results and keywords:
The results show as Array(0)
However, the keyword input appears to be functioning correctly.