when following a tutorial and making a single page app using laravel and vue.js. But at a certain point, an ajax request is not giving me the expected output. there is been trying many ways but nothing is working.
template I’m facing problem with
<template>
<v-container>
<v-form @submit.prevent=”create”>
<v-autocomplete
:items=”categories”
item-text=”name”
item-value=”id”
v-model=”form.category_id”
label=”Category”
\></v-autocomplete>
</template>
<script>
export default {
data() {
return {
form: {
title: null,
category_id: null,
body: null
},
categories: {}, //Expecting to populate the object with axios request.
errors: {}
};
},
created() {
axios.get(“/api/category”).then(res => (this.categories = res.data.data)); //This line is not populating the ‘categories’ object.
},
};
</script>
Category controller where I’m sending axios request
class CategoryController extends Controller
{
public function index()
{
return Category::latest()->get();
}
public function store(Request $request)
{
$category = new Category();
$category->name = $request->name;
$category->slug = Str::slug($request->name);
$category->save();
return response(‘Created’,Response::HTTP_CREATED);
}
public function show(Category $category)
{
return $category;
}
public function update(Request $request, Category $category)
{
$category->update([‘name’=>$request->name,’slug’=>Str::slug($request->name)]);
}
public function destroy(Category $category)
{
$category->delete();
return response(null,Response::HTTP_NO_CONTENT);
}
}
I expect to get the categories object to be populated with the axios request, but the categories boject is undefined
Solution :
Assuming that /api/category is for the index() method, the reason you’re not getting any results is because you’re not returning anything keyed by data (the 2nd in res.data.data), the information you need will be in res.data.
created() {
axios.get(“/api/category”)
.then(res => this.categories = res.data)
.catch(err => console.log(err));
},