xotriks_'s avatar

enable/disable e.g. div/span etc with database

Can someone tell me what I'm doing wrong?

DB: https://imgur.com/a/TI3ZnKE

web.php

Route::get('/', function () {
    return Inertia::render('Welcome', [
        'visibilities' => Visibility::all()
            ->map(fn($visible) => [
                'id' => $visible->id,
                'nameVisible' => $visible->nameVisible,
                'commentVisible' => $visible->commentVisible,
                'visible' => $visible->visible,
            ]),
    ]);
});

Vue

<script setup>
let props = defineProps({
    visibilities: Array,
});
</script>

<template>
  <div v-if="visibilities.id === 1 && visibilities.visible === 1">
    <span> test text </span>
  </div>
</template>
0 likes
9 replies
kokoshneta's avatar

Can someone tell me what I'm doing wrong?

Possibly, if you tell us what the problem is.

xotriks_'s avatar

@kokoshneta if I have it set this way, I don't see the div in the database, I have it set to true but it's not visible

Ben Taylor's avatar

Is your visible attribute being cast to a Boolean perhaps?

tykus's avatar
tykus
Best Answer
Level 104

There is a lot to fix here.

Lets look at the server side first - I don't know if you need all of the record if you intend to show only the visible ones. In any case, there is no need for the map operation if you simply get the attributes you need:

Route::get('/', function () {
    return Inertia::render('Welcome', [
        'visibilities' => Visibility::select(['id', 'nameVisible', 'commentVisible', 'visible'])->get()
    ]);
});

On the client-side, the visibilities prop is an Array of Objects, but you are trying to access an individual Object's properties such as id and visible directly. You need to iterate over visibilities to interrogate each individual Object and its properties:

<script setup>
let props = defineProps({
    visibilities: Array,
});
</script>

<template>
  <template v-for="visibility in props.visibilities">
    <div v-if="visibility.id === 1 && visibility.visible === 1">
      <span> test text </span>
    </div>
  </template>
</template>

Alternatively, you can organize the data in a computed property by filtering the Array for the elements you need.

Ultimately, it is better to (i) fetch only the data you need from the database and (ii) send the minimum data to Inertia

1 like
tykus's avatar

@kokoshneta forgot to close it in fact... we cannot put the v-for directive on the root template tag

xotriks_'s avatar

@tykus Thank you very much for your help! Now I just have to connect it to the administrator panel with a button or something like that to turn it on and off.

Please or to participate in this conversation.