I'm trying to show an image in Vue where the source is pulled from props (from Laravel). The props are there, but I can't get it to render in the browser. In fact, if I try to display any value on its own it shows up blank, which I assume is the problem.
Dashboard.vue
<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import { Head } from '@inertiajs/inertia-vue3';
import { Inertia } from "@inertiajs/inertia";
const props = defineProps({
games: {
type: Object,
default: () => ({}),
},
});
</script>
<template>
<Head title="Dashboard" />
<AuthenticatedLayout>
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Play a Game
</h2>
</template>
{{ $page.props.games.image }}
</AuthenticatedLayout>
</template>
If I remove '.image' and just use '$page.props.games', I get the full object.
[ { "id": 1, "name": "Memory", "image": "html://imagePath", "created_at": null, "updated_at": null } ]
Do I need to provide a more detailed model for the object and specify the types? Or is the problem somehow on the back end?
web.php
Route::get('/dashboard', [HomeController::class, 'index'])->name('dashboard');
HomeController.php
<?php
namespace App\Http\Controllers;
use Inertia\Inertia;
use App\Models\Game;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class HomeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
Log::debug(Game::all());
return Inertia::render(
'Dashboard',
[
'games' => Game::all()
]
);
}
}
Game.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Game extends Model
{
use HasFactory;
protected $fillable = [
'name',
'image',
];
}
My vue devtools don't show props.games either (I've read there's a problem with vue 3) or any other variables that I pass down and can use, so it's no help in determining what's happening.
As always, any help or suggestions on where to look next are appreciated.
You're getting not an object but an array
[ { "id": 1, "name": "Memory", "image": "html://imagePath", "created_at": null, "updated_at": null } ]
Game::all() return a collection. so you need to loop over games and get the image
<template v-for="game in $page.props.games">
{{ game.image }}
</template>