I just started to learn Vue 3 with Laravel, and I created an app where I have this:
Post Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title', 'content'
];
}
In PostsController, I have this function where I want to get all posts:
public function index()
{
$posts = Post::all();
return response()->json([
'posts' => $posts,
], 200);
}
In routes/api.php:
Route::get('/posts', [PostsController::class, 'index']);
And this is my Vue Component:
<template>
<div>
<ul>
<li v-for="post in posts" :key="post">
{{post.title}}
</li>
</ul>
</div>
</template>
<script>
export default {
data(){
return{
posts: []
}
},
created(){
fetch('http://vue-laravel.test/api/posts')
.then(response => {
console.log(response)
})
},
methods:{
}
}
</script>
This is the sample data:
{
"success": true,
"message": "List of all Posts",
"data": [
{
"id": 2,
"title": "Second",
"content": "Second post",
"created_at": "2021-01-27T08:08:21.000000Z",
"updated_at": "2021-01-27T08:08:21.000000Z"
},
{
"id": 1,
"title": "First",
"content": "This is my first post",
"created_at": null,
"updated_at": null
}
]
}
BUT when I console.log this fetch, I get this:
With console.log(response.data), I get undefined. Any suggestions?
