How do SPAs implement JS scripts?

I have a simple routing script which does the work for my SPA however, when it comes to implementing JS scripts for each page, it fails.

I am using simply using ‘fetch()’ to acquire the HTML and then ‘.innerHTML’. However, this does not execute JS scripts as we know and if I do make JS scripts execute and then navigate to another page and back, it fails because the specific variables are already allocated memory in the Virtual DOM leading to an error. How do I execute JS scripts with my simple JS routing?

Here is my router.js,

const mainEl = document.getElementsByTagName("main")[0];
let loc =
  window.location.search.replace("?loc=", "") !== ""
    ? window.location.search.replace("?loc=", "").split(".html")[0] + ".html"
    : "home.html";

function route(routeLoc) {
  if (routeLoc !== loc) {
    history.pushState({}, "", "?loc=" + routeLoc);
    render();
  }
}

async function render() {
  loc = window.location.search.replace("?loc=", "");
  const response = await fetch(loc);
  mainEl.innerHTML = await response.text();
}

window.pushstate = render;
window.onpopstate = render;
history.replaceState({}, "", "?loc=" + loc);
render();

raster layers “freeze” at the zoom they were first added and only refresh after I zoom

Problem:
I’m using Leaflet with georaster + georaster-layer-for-leaflet to toggle multiple single-band GeoTIFF rasters (only one visible at a time). When I switch which raster is visible, the previously added raster visually “sticks” at the zoom level where it was first rendered. The new raster doesn’t appear until I perform any zoom action; after a zoom, the correct raster shows up. In other words, the canvas seems frozen until a zoom* event fires.
All rasters are fetched over HTTPS from Firebase Storage (Cloud Storage for Firebase). Files are publicly readable through firebasestorage.googleapis.com. CORS is enabled on the bucket and allows GET/HEAD with Content-Type response header.

Example of what happened

The code:

(function (app) {
  'use strict';

  // -------------------------------------------------
  // Helpers
  // -------------------------------------------------
  function computeLegendRange(legend) {
    if (!legend || !Array.isArray(legend.classes) || legend.classes.length === 0) {
      return { min: 0, max: 1 };
    }
    const bounds = legend.classes
      .map(c => (typeof c.upper_bound === 'number' ? c.upper_bound : null))
      .filter(v => v !== null && isFinite(v));
    if (bounds.length === 0) {
      return { min: 0, max: 1 };
    }
    return { min: Math.min(...bounds), max: Math.max(...bounds) };
  }

  function createGeoRasterLayer(layerState) {
    const georaster = layerState.georaster;
    const config = layerState.config;
    const colorClasses = (config.legend && config.legend.classes) ? config.legend.classes : [];

    return new GeoRasterLayer({
      georaster: georaster,
      pane: layerState.paneId,
      opacity: 0.7,
      bounds: layerState.bounds,
      resolution: 256,
      updateWhenZooming: true,
      updateWhenIdle: true,
      updateInterval: 0,
      keepBuffer: 0,
      pixelValuesToColorFn: values => {
        const value = values[0];
        if (value === null || value === undefined || isNaN(value) || value === 0 || value === georaster.noDataValue) {
          return null;
        }
        const [minFilter, maxFilter] = layerState.filterRange;
        if (value < minFilter || value > maxFilter) {
          return null;
        }
        for (let i = 0; i < colorClasses.length; i++) {
          const cls = colorClasses[i];
          if (typeof cls.upper_bound === 'number' && value <= cls.upper_bound) {
            return cls.color || '#000';
          }
        }
        if (colorClasses.length) return colorClasses[colorClasses.length - 1].color || '#000';
        return '#000';
      }
    });
  }

  // -------------------------------------------------
  // Cleaning management
  // -------------------------------------------------
  function forceCleanupRasterLayer(layerId) {
    const layerState = app.activeRasterLayers[layerId];
    if (!layerState || !layerState.layer) return;

    if (app.map.hasLayer(layerState.layer)) {
      app.map.removeLayer(layerState.layer);
    }
    const pane = app.map.getPane(layerState.paneId);
    if (pane) pane.innerHTML = '';
    layerState.layer = null;
  }

  // -------------------------------------------------
  // UI Controls (Filter and Opacity)
  // -------------------------------------------------
  function applyRasterFilter(layerId) {
    const layerState = app.activeRasterLayers[layerId];
    if (layerState && layerState.layer) {
      forceCleanupRasterLayer(layerId);
      if (layerState.visible) {
        showRasterLayer(layerId);
        if (layerState.layer?.redraw) layerState.layer.redraw();
      }
    }
  }

  function createRangeFilterControl(layerId) {
    const layerState = app.activeRasterLayers[layerId];
    const { min, max } = layerState.legendRange;
    const [currentMin, currentMax] = layerState.filterRange;
    const container = document.createElement('div');
    container.className = 'range-filter-container';
    container.innerHTML = `
      <div class="range-labels">
        <span id="label-min-${layerId}">${currentMin.toFixed(1)}</span>
        <span id="label-max-${layerId}">${currentMax.toFixed(1)}</span>
      </div>
      <div class="range-slider">
        <div class="range-track"></div>
        <div class="range-selection" id="selection-${layerId}"></div>
        <input class="range-handle" id="slider-min-${layerId}" type="range" min="${min}" max="${max}" step="0.1" value="${currentMin}">
        <input class="range-handle" id="slider-max-${layerId}" type="range" min="${min}" max="${max}" step="0.1" value="${currentMax}">
      </div>`;

    const minSlider = container.querySelector(`#slider-min-${layerId}`);
    const maxSlider = container.querySelector(`#slider-max-${layerId}`);
    const minLabel = container.querySelector(`#label-min-${layerId}`);
    const maxLabel = container.querySelector(`#label-max-${layerId}`);
    const selection = container.querySelector(`#selection-${layerId}`);

    function updateSliderVisuals() {
      const minVal = parseFloat(minSlider.value);
      const maxVal = parseFloat(maxSlider.value);
      minLabel.textContent = minVal.toFixed(1);
      maxLabel.textContent = maxVal.toFixed(1);
      const range = max - min;
      if (range > 0) {
        const from = ((minVal - min) / range) * 100;
        const to = ((maxVal - min) / range) * 100;
        selection.style.left = `${from}%`;
        selection.style.right = `${100 - to}%`;
      }
    }

    function updateStateFromSliders() {
      let minVal = parseFloat(minSlider.value);
      let maxVal = parseFloat(maxSlider.value);
      if (minVal > maxVal) {
        [minVal, maxVal] = [maxVal, minVal];
        minSlider.value = minVal;
        maxSlider.value = maxVal;
      }
      layerState.filterRange = [minVal, maxVal];
      updateSliderVisuals();
    }
    minSlider.addEventListener('input', updateStateFromSliders);
    maxSlider.addEventListener('input', updateStateFromSliders);
    minSlider.addEventListener('change', () => applyRasterFilter(layerId));
    maxSlider.addEventListener('change', () => applyRasterFilter(layerId));
    updateSliderVisuals();
    return container;
  }

  function createOpacitySlider(layerId) {
    const layerState = app.activeRasterLayers[layerId];
    const controlContainer = document.createElement('div');
    controlContainer.className = 'opacity-control-container';
    const initialOpacity = layerState.layer ? layerState.layer.options.opacity : 0.7;
    controlContainer.innerHTML = `
      <i class="fas fa-eye"></i>
      <input type="range" min="0" max="1" step="0.05" value="${initialOpacity}" class="opacity-slider">
      <span>${Math.round(initialOpacity * 100)}%</span>`;
    controlContainer.querySelector('input').addEventListener('input', (e) => {
      const opacity = parseFloat(e.target.value);
      if (layerState.layer) layerState.layer.setOpacity(opacity);
      controlContainer.querySelector('span').textContent = `${Math.round(opacity * 100)}%`;
    });
    return controlContainer;
  }

  function toggleExtraControl(type, button, layerId, container) {
    const wasActive = button.classList.contains('active');
    document.querySelectorAll(`#wrapper_controls_${layerId} .opacity-tool-btn, #wrapper_controls_${layerId} .filter-tool-btn`).forEach(btn => btn.classList.remove('active'));
    container.innerHTML = '';
    container.style.display = 'none';
    if (!wasActive) {
      button.classList.add('active');
      const newControl = (type === 'opacity') ? createOpacitySlider(layerId) : createRangeFilterControl(layerId);
      container.appendChild(newControl);
      container.style.display = 'block';
    }
  }

  // -------------------------------------------------
  // Point analysis (value at the clicked point)
  // -------------------------------------------------
  function toggleInfoTool(button, layerId) {
    const layerState = app.activeRasterLayers[layerId];
    if (!layerState || !layerState.isLoaded) {
      alert('Por favor, carregue a camada primeiro.');
      return;
    }
    layerState.infoToolActive = !layerState.infoToolActive;
    button.classList.toggle('active', layerState.infoToolActive);
    const anyToolActive = Object.values(app.activeRasterLayers).some(state => state.infoToolActive);
    if (anyToolActive) {
      app.map.on('click', updatePixelValueOnClick);
    } else {
      app.map.off('click', updatePixelValueOnClick);
      const pixelValuePanel = document.getElementById('pixelValuePanel');
      if (pixelValuePanel) pixelValuePanel.style.display = 'none';
      if (app.clickPin) app.map.removeLayer(app.clickPin);
    }
  }

  function updatePixelValueOnClick(e) {
    const { lat, lng } = e.latlng;
    const panel = document.getElementById('pixelValuePanel');
    const content = document.getElementById('pixelValueContent');
    let htmlContent = `<b>Latitude:</b> ${lat.toFixed(4)}<br><b>Longitude:</b> ${lng.toFixed(4)}<hr style="margin: 5px 0;">`;
    for (const layerId in app.activeRasterLayers) {
      const layerState = app.activeRasterLayers[layerId];
      if (layerState.visible && layerState.infoToolActive && layerState.georaster) {
        const georaster = layerState.georaster;
        let valueText = 'Fora da área de dados';
        if (lng >= georaster.xmin && lng <= georaster.xmax && lat >= georaster.ymin && lat <= georaster.ymax) {
          try {
            const x = Math.floor((lng - georaster.xmin) / georaster.pixelWidth);
            const y = Math.floor((georaster.ymax - lat) / georaster.pixelHeight);
            const pixelValue = georaster.values[0][y][x];
            if (pixelValue !== georaster.noDataValue && !isNaN(pixelValue) && pixelValue !== 0) {
              const unit = layerState.config.unit || '';
              valueText = `${pixelValue.toFixed(2)} ${unit}`;
            }
          } catch (err) { }
        }
        htmlContent += `<b>${layerState.config.name}:</b> ${valueText}<br>`;
      }
    }
    content.innerHTML = htmlContent;
    panel.style.display = 'block';
    if (app.clickPin) app.map.removeLayer(app.clickPin);
    app.clickPin = L.marker(e.latlng).addTo(app.map);
    const removePinBtn = document.getElementById('removeAnalysisPinBtn');
    if (removePinBtn) removePinBtn.style.display = 'block';
  }

  function createOperationalControls(layerId, controlsWrapper, controlsContainer) {
    controlsWrapper.innerHTML = '';
    const infoBtn = document.createElement('i');
    infoBtn.className = 'fas fa-info-circle layer-action-icon info-tool-btn';
    infoBtn.title = 'Análise de Ponto';
    infoBtn.dataset.layerId = layerId;
    controlsWrapper.appendChild(infoBtn);
    const opacityBtn = document.createElement('i');
    opacityBtn.className = 'fas fa-eye layer-action-icon opacity-tool-btn';
    opacityBtn.title = 'Ajustar opacidade';
    controlsWrapper.appendChild(opacityBtn);
    const filterBtn = document.createElement('i');
    filterBtn.className = 'fas fa-sliders-h layer-action-icon filter-tool-btn';
    filterBtn.title = 'Filtrar valores de pixel';
    controlsWrapper.appendChild(filterBtn);
    infoBtn.addEventListener('click', () => toggleInfoTool(infoBtn, layerId));
    opacityBtn.addEventListener('click', () => toggleExtraControl('opacity', opacityBtn, layerId, controlsContainer));
    filterBtn.addEventListener('click', () => toggleExtraControl('filter', filterBtn, layerId, controlsContainer));
  }

  // -------------------------------------------------
  // Layer Visibility
  // -------------------------------------------------
  function hideRasterLayer(id) {
    const st = app.activeRasterLayers[id];
    if (!st) return;

    forceCleanupRasterLayer(id);
    st.visible = false;

    if (st.infoToolActive) {
      const infoBtn = document.querySelector(`.info-tool-btn[data-layer-id="${id}"]`);
      if (infoBtn) infoBtn.classList.remove('active');
      st.infoToolActive = false;
      const anyToolActive = Object.values(app.activeRasterLayers).some(state => state.infoToolActive);
      if (!anyToolActive) {
        app.map.off('click', updatePixelValueOnClick);
        const panel = document.getElementById('pixelValuePanel');
        if (panel) panel.style.display = 'none';
        if (app.clickPin) app.map.removeLayer(app.clickPin);
      }
    }
  }

  function showRasterLayer(id) {
    const st = app.activeRasterLayers[id];
    if (!st || !st.georaster) return;

    st.paneId = `raster-${id}`;
    if (!app.map.getPane(st.paneId)) {
      app.map.createPane(st.paneId);
      // app.__rZ = (app.__rZ || 1050) + 1;
      app.map.getPane(st.paneId).style.zIndex = app.__rZ;
    }
    if (st.layer) {
      forceCleanupRasterLayer(id);
    }
    st.layer = createGeoRasterLayer(st);
    st.visible = true;
    st.layer.addTo(app.map);
    if (typeof st.layer.redraw === 'function') {
      st.layer.redraw();
    }
    app.map.once('idle', () => { if (st.visible && st.layer?.redraw) st.layer.redraw(); });
    app.map.once('zoomend', () => { if (st.visible && st.layer?.redraw) st.layer.redraw(); });
  }

  // -------------------------------------------------
  // Raster loading
  // -------------------------------------------------
  async function loadRasterLayer(layerId) {
    const layerState = app.activeRasterLayers[layerId];
    const config = layerState.config;
    const icon = document.getElementById(`icon_${layerId}`);
    icon.className = 'fas fa-spinner fa-spin layer-action-icon';

    try {
      const response = await fetch(config.path, { mode: 'cors' });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const arrayBuffer = await response.arrayBuffer();
      const georaster = await parseGeoraster(arrayBuffer);

      layerState.georaster = georaster;
      layerState.bounds = L.latLngBounds([
        [georaster.ymin, georaster.xmin],
        [georaster.ymax, georaster.xmax]
      ]);
      layerState.legendRange = computeLegendRange(config.legend);
      layerState.filterRange = [layerState.legendRange.min, layerState.legendRange.max];
      layerState.isLoaded = true;

      const checkbox = document.getElementById(`cb_${layerId}`);
      checkbox.disabled = false;
      checkbox.checked = true;
      checkbox.dispatchEvent(new Event('change', { bubbles: true }));

      const controlsWrapper = document.getElementById(`wrapper_controls_${layerId}`);
      const controlsContainer = document.getElementById(`controls_${layerId}`);
      createOperationalControls(layerId, controlsWrapper, controlsContainer);
      icon.className = 'fas fa-check layer-action-icon';
      setTimeout(() => { icon.className = 'fas fa-download layer-action-icon'; }, 1200);
    } catch (error) {
      console.error(`Falha ao carregar camada raster ${layerId}:`, error);
      icon.className = 'fas fa-download layer-action-icon';
      alert(`Não foi possível carregar a camada ${config.name}.`);
    }
  }

  // -------------------------------------------------
  // Initialization
  // -------------------------------------------------
  function init() {
    // Point Analysis Panel Configuration
    const panelHeader = document.querySelector('#pixelValuePanel .popup-header h4');
    if (panelHeader) panelHeader.innerHTML = `<i class="fas fa-chart-area"></i> Análise de Ponto`;
    const panelContent = document.getElementById('pixelValueContent');
    if (panelContent) {
      const removePinBtn = document.createElement('button');
      removePinBtn.id = 'removeAnalysisPinBtn';
      removePinBtn.className = 'panel-action-button danger';
      removePinBtn.innerHTML = '<i class="fas fa-times-circle"></i> Remover Marcador';
      removePinBtn.style.cssText = 'display: none; width: 100%; margin-top: 10px;';
      panelContent.after(removePinBtn);
      removePinBtn.addEventListener('click', () => {
        if (app.clickPin) {
          app.map.removeLayer(app.clickPin);
          app.clickPin = null;
          removePinBtn.style.display = 'none';
        }
      });
    }
    const closeBtn = document.getElementById('closePixelValuePanel');
    if (closeBtn) {
      closeBtn.addEventListener('click', () => {
        Object.keys(app.activeRasterLayers).forEach(layerId => {
          const layerState = app.activeRasterLayers[layerId];
          if (layerState.infoToolActive) {
            layerState.infoToolActive = false;
            const infoBtn = document.querySelector(`.info-tool-btn[data-layer-id="${layerId}"]`);
            if (infoBtn) infoBtn.classList.remove('active');
          }
        });
        app.map.off('click', updatePixelValueOnClick);
        const pixelValuePanel = document.getElementById('pixelValuePanel');
        if (pixelValuePanel) pixelValuePanel.style.display = 'none';
        if (app.clickPin) app.map.removeLayer(app.clickPin);
      });
    }

    // Building the Layer UI
    const rasterList = app.config.rasterLayers;
    if (!Array.isArray(rasterList) || rasterList.length === 0) return;
    app.activeRasterLayers = app.activeRasterLayers || {};
    rasterList.forEach(rasterConfig => {
      const groupContainer = document.getElementById(`group-content-${rasterConfig.group}`);
      if (!groupContainer) return;

      const layerId = rasterConfig.id;
      app.activeRasterLayers[layerId] = {
        layer: null, config: rasterConfig, georaster: null,
        visible: false, isLoaded: false, filterRange: null,
        bounds: null, legendRange: computeLegendRange(rasterConfig.legend),
        infoToolActive: false, paneId: null,
        legend: { type: 'raster', title: rasterConfig.name, ...(rasterConfig.legend || {}) }
      };
      const listItem = document.createElement('div');
      listItem.className = 'layer-group-item';
      listItem.innerHTML = `
        <div class="layer-item" data-layer-id="${layerId}">
          <i class="fas fa-grip-vertical layer-drag-handle"></i>
          <input type="checkbox" id="cb_${layerId}" disabled>
          <label for="cb_${layerId}">${rasterConfig.name}</label>
          <div class="layer-controls-wrapper" id="wrapper_controls_${layerId}">
            <i class="fas fa-download layer-action-icon" id="icon_${layerId}" title="Carregar camada"></i>
          </div>
        </div>
        <div class="raster-controls" id="controls_${layerId}" style="display: none;"></div>`;
      groupContainer.appendChild(listItem);
      document.getElementById(`icon_${layerId}`).addEventListener('click', () => loadRasterLayer(layerId));

      const checkbox = document.getElementById(`cb_${layerId}`);
      checkbox.addEventListener('change', (e) => {
        const isChecked = e.target.checked;
        if (!app.activeRasterLayers[layerId].isLoaded) { e.target.checked = false; return; }

        if (isChecked) {
          Object.keys(app.activeRasterLayers).forEach(otherId => {
            if (otherId !== layerId && app.activeRasterLayers[otherId]?.visible) {
              const cb = document.getElementById(`cb_${otherId}`);
              if (cb) cb.checked = false;
              hideRasterLayer(otherId);
            }
          });
          showRasterLayer(layerId);
        } else {
          hideRasterLayer(layerId);
        }
        if (app.legend && app.legend.update) {
          app.legend.update();
        }
      });
    });
  }

  // -------------------------------------------------
  // Public API
  // -------------------------------------------------
  app.raster = {
    init,
    loadRasterLayer,
    showRasterLayer,
    hideRasterLayer,
    toggleInfoTool,
    updatePixelValueOnClick
  };
  app.initRasterLayers = init;

})(window.app = window.app || {});

Questions:

*- Is there a known issue with GeoRasterLayer (or its L.GridLayer internals) where the canvas doesn’t invalidate until a zoom?

  • Is there a recommended way to fully dispose/destroy a GeoRasterLayer so that switching rasters forces a fresh render without needing a zoom?
  • Is creating a separate pane per raster contributing to the issue (z-index/canvas stacking), and should I reuse a single dedicated pane for all rasters instead?
  • Any hook I should call (e.g., map.invalidateSize() with options, or a different redraw/clear path) to force immediate repaint on toggle?*

What actually happens:
When I toggle visibility (A → B), raster B should render immediately (no zoom/pan required) and the canvas from raster A should be fully cleared. After toggling, the screen still shows raster A at the zoom level where it was first added. Only after a zoom (in or out) does raster B render.

What I’ve tried:

*- Calling layer.redraw() right after addTo(map) and also on map.once(‘idle’) / map.once(‘zoomend’).

  • Using keepBuffer: 0, updateWhenZooming: true, updateWhenIdle: true, updateInterval: 0.
  • Removing the layer and clearing the pane’s DOM (pane.innerHTML = ”) before recreating.
  • Ensuring only one raster layer is visible at a time (checkbox logic toggles A/B).
  • Verifying CORS and fetch; data loads fine and pixels are read correctly.
  • Confirming no leftover global listeners are required; I don’t rely on zoomstart/zoomend to trigger the first render.*

How can I use the code of HTML, CSS and JS consisting of different animations and styles into the WordPress? [closed]

I liked some animations and styles in a website. I have the code (HTML, CSS, JS) where I have a website built with WordPress. Tried to use the code in the page but no use, its not working out.Also the maximum animations and effects are written in JavaScript. So how and where can I find the best animations and effects, any sources?

Tried to import the php file and short code and muchmore. I thought the animations would work. Like they are on hover animations?

Prisma database setup for Cal.com

I am trying to setup a database for calcom locally on my System, so that I can contribute open-source code.

I have already seeded the database by running this syntax, yarn workspace @calcom/prisma prisma migrate dev

and when I try to generate the prisma client, run yarn workspace @calcom/prisma prisma generate

and yet, I keep getting this error message.

PrismaClientKnownRequestError: 


Invalid `prisma.user.count()` invocation:

The table `public.users` does not exist in the current database.

Laravel blade mail data not rendered

I have a mail view named passwordReset.blade.php like this

<!DOCTYPE html>
<html>
<head>
    <title>Wachtwoord Reset</title>
    <style>
        body {
            font-family: "Calibri", sans-serif;
            color: #000000;
            font-size: 0.9167em;
        }
        .token {
            color: #00a9b5;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <p>Beste gebruiker van de ,</p>
    <p>
        Er is een aanvraag gedaan voor het herstellen van je wachtwoord. Ben je dit niet geweest dan mag je deze e-mail negeren. Voor het opnieuw instellen van je wachtwoord voer je de onderstaande code in bij de app:
    </p>
    <p class="token">
        {{ $code }}
    </p>
    <p>
        Let op! Deze code is 30 minuten geldig.
    </p>

    <p>
        Hartelijke groet,
    </p>
</body>
</html>

But in the mail the code stays like this: {{ $code }}

This is my mailable class:

<?php

namespace AppMail;

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateMailMailable;
use IlluminateMailMailablesContent;
use IlluminateMailMailablesEnvelope;
use IlluminateQueueSerializesModels;
use AppModelsUser;

class PasswordResetNew extends Mailable
{
    use Queueable, SerializesModels;

    private User $user;
    /**
     * Create a new message instance.
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'emails.passwordReset',
            with: [
                'code' => $this->user->USER_WACHTWOORD_RESETCODE,

            ],
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, IlluminateMailMailablesAttachment>
     */
    public function attachments(): array
    {
        return [];
    }
}

And i have already debugged and the value is not empty before in the constructor and content functions.

And this mail gets called like this:
Mail::to($user->USER_EMAIL)
->send(new PasswordResetNew($user));

Thanks

How to fix “Class not found” error in Laravel 10 when running artisan command?

I’m working on a Laravel 10 project and ran into a Class not found error when executing an artisan command.

Goal: I want to create a custom artisan command that fetches data from the database.

Problem: When I run

php artisan fetch:data

I get the following error:

Target class [AppConsoleCommandsFetchData] does not exist.

What I’ve tried

  • Checked that my class FetchData.php exists under app/Console/Commands/.

  • Verified that the namespace is correct (namespace AppConsoleCommands;).

  • Registered the command inside app/Console/Kernel.php under $commands.

  • Ran composer dump-autoload.

Expected result

The artisan command should run successfully and fetch the data.

Actual result

I keep getting the Class not found error.

Error message:

In Container.php line 895:
Target class [AppConsoleCommandsFetchData] does not exist.

What could be the reason for this error and how can I fix it?

Make array of Variables with osclass custom category values

How can i make an array of veriables generated using the values passed through a while loop

I am using osclass for a uni project and i find no way whatsoever to make a list os usable variables from the custom catagory fields i added.

I have made Identifiers for the custom catagories also ( SLUGs )
and have tried many different approaches to grab and echo the custom catagory values elsewhere on the page

I cannot isolate the custom catagory values by any means.

Below is the code used to display the custom catagory values on my osclass page

<?php if( osc_count_item_meta() >= 1 ) { ?> 
   
          <?php while ( osc_has_item_meta() ) { ?>
          
                    <?php if(osc_item_meta_value()!='') { ?> 
                   
                   
                    // I WOULD LIKE TO MAKE MAKE AN ARRAY OF VERIABLES SO I CAN USE THE CUSTOM CATAGORY DATA 
                    // TRIED SO FAR if(osc_item_meta_name()!='') {  $caughtcountry = osc_item_meta_value('country'); } 
                    // BUT THIS APPROACH DOES NOT WORK 

                    <?php } ?>
            
          <?php } ?>
          
          
      
    <?php } ?>`
    

I have tried using the identifiers that i added to the catagory in Admin panel

I have also tried using the Current PHP but cannot grab the values of specific custom catagories

Below is an example of one of my attempts to grab a custom catagory value but it only shows the 1st value within the values instead of cataching the ‘age’ value using the ‘age’ identifier i used.

 <?php if( osc_count_item_meta() >0 ) {  // The If osc_count_item_meta() >=1 
      if(osc_item_meta_value('age')!='') {  $caughtage = osc_item_meta_value('age'); }  else { $caughtage=''; }
                
    }   else { $caughtage=''; }
     ?>

Also tried the following

<?php if( osc_count_item_meta() >0 ) { 

      if(osc_item_meta_name('age')!='') {  $caughtage = osc_item_meta_value('age'); }  else { $caughtage=''; }
                
    }   else { $caughtage=''; }
     ?>

Have also tried common sense but that doesnt work either

<?php if( osc_item_age()!='' ) { $Age = osc_item_age(); } else {$Age='';} ?>

I am completely stumped.

The code below loops through the custom catagories but isolating them into variables im struggling with, yet i imagine it would be as easy as an array loop

<?php if( osc_count_item_meta() >= 1 ) { ?> 

<div id="custom_fields">
<div class="meta_list">

    <?php while ( osc_has_item_meta() ) { ?>
        <?php if(osc_item_meta_value()!='') { ?> 
            <div class="meta">
                <strong><?php echo osc_item_meta_name(); ?>:</strong> 
                <span><?php echo osc_item_meta_value(); ?></span>
            </div>

        <?php } ?>
    <?php } ?>
<?php } ?>
    
  
<?php } ?>

Any help would be greatly appreciated.

Laravel testing database table is being accessed by other users

I’m currently building a multi-tenant application using stancl/tenancy (every tenant uses their own database) in my Laravel application.

Whenever I’m writing tests, tests fail a lot due to the error

IlluminateDatabaseQueryException: SQLSTATE[55006]: Object in use: 7 FEHLER:  auf Datenbank »tenant_019949ce« wird von anderen Benutzern zugegriffen
DETAIL:  1 andere Sitzung verwendet die Datenbank. (Connection: tenant_host_connection, SQL: DROP DATABASE "tenant_019949ce")

which means the table is used by another user. Tables are created when a tenant is created and should be deleted if a tenant gets deleted but it always fails in tearDown method.

My tests extend TenancyTestCase class:

use IlluminateFoundationTestingTestCase as BaseTestCase;

class TenancyTestCase extends BaseTestCase {

    use RefreshDatabase;

    private Tenant $tenant;

    protected function setUp(): void {
        parent::setUp();

        Config::set('tenancy.seeder_parameters.--class', TestDatabaseSeeder::class);

        $this->setupDefaultTenant();
        $this->forceRootUrl();

        $this->withoutVite();
    }

    private function setupDefaultTenant(): void {

        $this->tenant = Tenant::factory()->create();
        $this->tenant->domains()->save(Domain::factory([
            'domain' => 'tenant',
        ])->make());

        tenancy()->initialize($this->tenant);
    }

    private function forceRootUrl(): void {
        $parsed = parse_url(config('app.url'));
        $host = $parsed['host'] ?? 'localhost.test';
        $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';

        URL::forceRootUrl('https://tenant.' . $host . $port);
    }

    public function tearDown(): void {
        tenancy()->end();
        $this->tenant->delete();

        parent::tearDown();
    }
}

I couldn’t figure out why yet, any ideas on how to fix this?

My goal is to create a single database for each test and delete them if test is completed.

Thank you.

Laravel form submission not saving to database and file uploads not working

I am working on a scholarship management system using Laravel 12, Laravel Breeze, Blade, Tailwind, and MySQL. I created a multi-step applicant form with text fields and file uploads (passport photo, Form 137, certificates, etc.).

When I submit the form, the page reloads but the data is not being saved to the database, and the uploaded files are not stored in the storage/app/public folder.

I expected the form data to be inserted into the database and the uploaded files to be saved in storage, then accessible from the admin dashboard.

I already:

Used enctype=”multipart/form-data” in my form.

Added protected $fillable in my model.

Ran migrations for the fields.

Tried using php artisan storage:link to link storage.

But the problem is still the same: no data is saved, and files don’t upload.

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsApplicationForm;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesStorage;

class ApplicationFormController extends Controller
{
    /**
     * Show the application form for applicants.
     */
    public function create($program)
    {
        // Validate program
        if (!in_array($program, ['DOST', 'CHED'])) {
            abort(404); // If invalid program, show 404
        }

        // Pass the program to your Blade view
        return view('applicant.application-form', compact('program'));
    }

    /**
     * Store a newly created application form in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            // Basic info
            'last_name' => 'required|string|max:255',
            'first_name' => 'required|string|max:255',
            'middle_name' => 'nullable|string|max:255',
            'academic_year' => 'nullable|string|max:255',
            'school_term' => 'nullable|string|max:255',
            'application_no' => 'nullable|string|max:255',
            'program' => 'required|string|in:DOST,CHED',

            // Contact / personal details
            'birthdate' => 'nullable|date',
            'gender' => 'nullable|string|max:20',
            'civil_status' => 'nullable|string|max:50',
            'address' => 'nullable|string|max:500',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:50',

            // Academic background
            'bs_field' => 'nullable|string|max:255',
            'bs_university' => 'nullable|string|max:255',
            'bs_scholarship_type' => 'nullable|string|max:255',
            'bs_scholarship_others' => 'nullable|string|max:255',
            'bs_remarks' => 'nullable|string|max:500',

            // Graduate intent
            'grad_field' => 'nullable|string|max:255',
            'grad_university' => 'nullable|string|max:255',
            'grad_plan' => 'nullable|string|max:255',

            // Employment
            'employer_name' => 'nullable|string|max:255',
            'employer_address' => 'nullable|string|max:500',
            'position' => 'nullable|string|max:255',
            'employment_status' => 'nullable|string|max:255',

            // Research & plans
            'research_title' => 'nullable|string|max:500',
            'career_plan' => 'nullable|string|max:500',

            // File uploads
            'passport_picture' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:4096',
            'form137' => 'nullable|file|mimes:pdf|max:4096',
            'cert_employment' => 'nullable|file|mimes:pdf|max:4096',
            'cert_purpose' => 'nullable|file|mimes:pdf|max:4096',

            'birth_certificate_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'transcript_of_record_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'endorsement_1_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'endorsement_2_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'recommendation_head_agency_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'form_2a_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'form_2b_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'form_a_research_plans_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'form_b_career_plans_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'form_c_health_status_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'nbi_clearance_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'letter_of_admission_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'approved_program_of_study_pdf' => 'nullable|file|mimes:pdf|max:4096',
            'lateral_certification_pdf' => 'nullable|file|mimes:pdf|max:4096',

            // Declaration
            'terms_and_conditions_agreed' => 'nullable|boolean',
            'applicant_signature' => 'nullable|string|max:255',
            'declaration_date' => 'nullable|date',
        ]);

        $application = new ApplicationForm();
        $application->user_id = Auth::id();
        $application->program = $request->program;
        $application->status = 'pending';
        $application->submitted_at = now();

        // Fill non-file fields
        $application->fill(collect($validated)->except([
            'passport_picture',
            'form137',
            'cert_employment',
            'cert_purpose',
            'birth_certificate_pdf',
            'transcript_of_record_pdf',
            'endorsement_1_pdf',
            'endorsement_2_pdf',
            'recommendation_head_agency_pdf',
            'form_2a_pdf',
            'form_2b_pdf',
            'form_a_research_plans_pdf',
            'form_b_career_plans_pdf',
            'form_c_health_status_pdf',
            'nbi_clearance_pdf',
            'letter_of_admission_pdf',
            'approved_program_of_study_pdf',
            'lateral_certification_pdf',
        ])->toArray());

        // File uploads
        $fileFields = [
            'passport_picture',
            'form137',
            'cert_employment',
            'cert_purpose',
            'birth_certificate_pdf',
            'transcript_of_record_pdf',
            'endorsement_1_pdf',
            'endorsement_2_pdf',
            'recommendation_head_agency_pdf',
            'form_2a_pdf',
            'form_2b_pdf',
            'form_a_research_plans_pdf',
            'form_b_career_plans_pdf',
            'form_c_health_status_pdf',
            'nbi_clearance_pdf',
            'letter_of_admission_pdf',
            'approved_program_of_study_pdf',
            'lateral_certification_pdf',
        ];

        foreach ($fileFields as $field) {
            if ($request->hasFile($field)) {
                $path = $request->file($field)->store("uploads/application_forms", "public");
                $application->$field = $path;
            }
        }

        $application->save();

        return redirect()->route('dashboard')
            ->with('success', 'Application form submitted successfully.');
    }

    /**
     * Update an existing application form.
     */
    public function update(Request $request, $id)
    {
        $application = ApplicationForm::findOrFail($id);

        // Ensure only the owner can update
        if ($application->user_id !== Auth::id()) {
            abort(403, 'Unauthorized action.');
        }

        $validated = $request->validate([
            'program' => 'required|string|max:255',
            'school' => 'required|string|max:255',
            'year_level' => 'required|string|max:50',
            'reason' => 'nullable|string|max:1000',
            // file fields
            'passport_picture' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
            'form137' => 'nullable|mimes:pdf,jpg,jpeg,png|max:4096',
            'cert_employment' => 'nullable|mimes:pdf,jpg,jpeg,png|max:4096',
            'cert_purpose' => 'nullable|mimes:pdf,jpg,jpeg,png|max:4096',
        ]);

        // Update normal fields
        $application->program = $validated['program'];
        $application->school = $validated['school'];
        $application->year_level = $validated['year_level'];
        $application->reason = $validated['reason'] ?? $application->reason;

        // Handle file uploads (optional replacement)
        if ($request->hasFile('passport_picture')) {
            $application->passport_picture = $request->file('passport_picture')->store('uploads/passport', 'public');
        }

        if ($request->hasFile('form137')) {
            $application->form137 = $request->file('form137')->store('uploads/form137', 'public');
        }

        if ($request->hasFile('cert_employment')) {
            $application->cert_employment = $request->file('cert_employment')->store('uploads/employment', 'public');
        }

        if ($request->hasFile('cert_purpose')) {
            $application->cert_purpose = $request->file('cert_purpose')->store('uploads/purpose', 'public');
        }

        // Keep status "pending" after edit
        $application->status = 'pending';
        $application->save();

        return redirect()->route('applicant.myApplication')
            ->with('success', 'Your application has been updated and set to Pending.');
    }

    /**
     * Show all applications submitted by the logged-in user.
     */
    public function viewMyApplication()
    {
        $applications = auth()->user()->applicationForms()->latest()->get();
        return view('applicant.my-application', compact('applications'));
    }

    public function edit($id)
    {
        $application = ApplicationForm::findOrFail($id);

        if ($application->user_id !== Auth::id()) {
            abort(403, 'Unauthorized action.');
        }

        return view('applicant.application-edit', compact('application'));
    }
}

Angular – non-existing circular dependency detected (!)

I’m getting the message in console:

Circular dependency detected for MyService. Source: Environment

…however, that service is being injected in only one component, and obviously – that component isn’t injected in service.

This message is listed in console few times, but stack-trace says nothing. Any ideas?

Angular version: 20.x, Vite

stack trace

Set a Viewport to have a margin (or padding) on the right-hand side?

I have a FileMaker file, which uses a web-viewer as a Rich Text Editor. I also have a ‘Slide Control’ which slides a layout object in from one side. When this happens, I run a Function in the RTE which resizes it by adding Padding to one side. I’d like to do the same thing, for a web-viewer that’s being used for browsing the internet.

So essentially, I’m trying to have a clear space to one side of any given web page.

Is this possible to achieve with a Viewport???

This is what I use to resize my RTE:

function changeStyle(PadLeft, PadRight){
var element = document.getElementById('defaultRTE');
element.style.paddingLeft = (PadLeft);
element.style.paddingRight = (PadRight);
}

(NB.. I’m an amateur)

Why does npm run dev fail with “vite is not recognized as an internal or external command” in Laravel 10?

I recently installed a fresh Laravel 10 project with Vite as the frontend build tool. After running composer install and npm install, I tried to start the development server with:

npm run dev

But I get this error on Windows:

'vite' is not recognized as an internal or external command,
operable program or batch file.

I have:

  • Deleted node_modules and re-run npm install.

  • Ensured that vite is listed in devDependencies inside package.json.

  • Tried running npx vite directly, but it shows the same error.

  • Cleared cache with npm cache clean --force.

Expected result: running npm run dev should start the Laravel Vite dev server and compile my assets.

Actual result: it throws the “vite is not recognized” error and does not run.

What is the correct way to fix this issue and ensure npm run dev works properly with Laravel 10 and Vite?

Preflight Request Failure Handling Axios

error image

when i put rate limiting on my server , and when rate exceeds the preflight request fails so code execution stops and interceptor error is also not shown is there any way to handle it in axios , in axios interceptor

 api.interceptors.response.use(
  res => res,
  err => {
    }
  }
);