Guide on showing Laravel variables as JSON in Laravel view with Charts.js

I am currently working on a project using Laravel 7 with MySQL and Charts.js. I'm facing an issue in echoing/displaying the data of two columns ("player_name" and "kills") from my MySQL database in JSON format. Typically, Laravel provides a @foreach loop for displaying data like this:

@php
    foreach($player_stats as $player) {
        echo "['".$player->player_name."', ".$player->kills."],";
    }
@endphp

However, I am unsure about how to incorporate this within my JavaScript/JSON code. Can someone help me out? Here is the error message I encounter along with the remaining parts of my code:

Error message:

Facade\Ignition\Exceptions\ViewException
Undefined variable: player_name (View: C:\wamp64\www\GeneralTesting\resources\views\show-players.blade.php)
... More sections of code go here ...

Answer №1

Start by converting your outcome into the desired format

class PlayerController extends Controller
{
    public function playerStatistics() {
        $players = Player::all();
        $playerNames[] = $players->pluck('player_name');
        $playerKills[] = $players->pluck('kills');
        return view("show-players", compact(['playerNames', 'players', 'playerKills']));
    }
}

Next, use @json in your JavaScript code

<script >
var playerKillsData = @json($playerKills);

var kills = [playerKillsData];

var playerNamesData = @json($playerNames);

var names = [playerNamesData];

var canvas = document.getElementById('graphCanvas').getContext('2d');
var myChart = new Chart(canvas, {
    type: 'bar',
    data: {
        labels: names[0],
        datasets: [{
            label: 'Player Name',
            data: kills[0],
            backgroundColor: ['rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
}); 
</script>

Answer №2

I managed to avoid the loop and successfully implement the chart.js bar chart (some refactoring required)

Controller (PlayerController.php):

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Player;

class PlayerController extends Controller
{
    public function playerstats() {
        // $players = Player::all();
        $players = Player::all()->toArray();
        $player_kills = array_map(function($player) {
          return $player['kills'];
        }, $players);
        $player_names = array_map(function($player) {
          return $player['player_name'];
        }, $players);
        // return view("show-players", compact("player_stats"));
        return view("show-players", compact(['player_kills',
                                             'players',
                                             'player_names']));
    }
}

View (show-player.blade.php)

<script >
    var player_kills = @json($player_kills);
// console.log(player_kills); 
var kills = [player_kills];

var player_names = @json($player_names);
// console.log(player_names); 
var p_names = [player_names];

var ctx = document.getElementById('graphCanvas').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: p_names[0],
        datasets: [{
            label: 'player name',
            data: kills[0],
            backgroundColor: ['rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
}); 
</script>

Answer №3

Implement this code snippet in your controller:

dump($data);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble connecting to Docker? The webpage at localhost seems to be unresponsive and is not providing any data. Error: ERR_EMPTY_RESPONSE

Currently in the process of mastering docker, kafka, and python. My objective is to leverage python for extracting data from json files and transmitting them to kafka. The setup seems to be functioning properly, but I'm facing challenges with viewin ...

issues with passing values on second click using ajax and jquery

Just starting out with JavaScript, jQuery, and AJAX and running into issues with a basic script to load more data from a database upon button clicks. The first load more button click works fine. But subsequent clicks do not pass values and do not execute. ...

Managing user roles in Nova with the help of Spatie Laravel Permissions

I'm currently utilizing the Spatie Laravel Permissions package in a Laravel 5.8 project and incorporating Nova for administrative tasks. My goal is to allow the super admin user to assign roles to selected users directly from the Nova dashboard. To a ...

Exploring the concept of recursive method calls in TypeScript

I am trying to call the filterArr method inside the filterArr itself. Here is my current implementation: function filterArr(array, search) { var result = []; array.forEach((a)=> { var temp = [], o = {}, ...

Styling CSS according to the specific words found within the content

After retrieving text data from an API, I want to enclose a specific word, for example "Biography", with <span> and </span> tags in order to apply unique styling. Can anyone provide guidance on how to accomplish this using jQuery or JavaScrip ...

A guide to linking data retrieved from getJSON to state in ReactJS

After numerous attempts, I am still struggling to retrieve data from a JSON file and integrate it into my webpage using ReactJS <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8> <title>Demo Fetch</title ...

Having trouble retrieving text using getText() or getAttribute("innerHTML")

getAttribute but struggling to retrieve the text associated with each combobox. I need to access the text content of every combobox. <small> <input type="checkbox" checked="checked" value="on" name="irOperations[0]"/> Account Activity < ...

A guide to quickly obtaining the width and height of an element as it resizes in Vue.js

Is there a way to immediately get the width and height of an element when it is resizing in Vue.js? I have created a Codepen illustration and would appreciate any help in making it function correctly, thank you! Codepen let app = new Vue({ el: &apos ...

Cloud Firestore trigger fails to activate Cloud function

I am facing an issue with triggering a Cloud Function using the Cloud Firestore trigger. The function is supposed to perform a full export of my sub collection 'reviews' every time a new document is added to it. Despite deploying the function suc ...

Is there a solution for the continuous automatic incrementing of the jQuery UI spinner that occurs when I right-click on it?

Only Linux and Mac OS users are facing this particular issue, indicating a potential bug with the jQuery spinner. The bug also affects the spinner located at the following link: https://jqueryui.com/spinner/ <input class="spinner"/> $(".spinner"). ...

What is the best way to retrieve a button's value upon clicking and display it in a React component?

Picture a calculator display. Each button press should output the value of that button once, and if pressed multiple times, the value should be displayed accordingly. import { useState } from "react"; function App() { const [data, setData] = ...

Transform the JSON data into a Map containing key-value pairs of type String

I have a JSON input that looks like this: {"a": "x", "b": "y", "c": "z", .... } My goal is to convert this JSON into a Map of type Map[String, String] This map should consist of key-value pairs. Is there a way to achieve this using circe? Keep in mind ...

Removing the empty option in a select element with ng-model

There's a situation I'm dealing with that involves a select dropdown along with a refresh button and a plus button. The issue arises when clicking the refresh button sets the model to null, while clicking the plus button displays the dropdown wit ...

Merging rows with the highest and lowest IDs in MySQL

I'm currently working with a table that stores entrance data for employees. IO_Id Employee_Id EnterDate EnterTime ExitDate ExitTime -------------------------------------------------------------------------- 1 1 11/20/20 ...

Troubleshooting the clonewithrows array problem in react-native

I am currently facing an issue while trying to populate a Listview in my react-native application using data from Firebase. The error message I am receiving is as follows: "Objects are not valid as a React child (found object with keys {title}). If you me ...

Combining JavaScript files into a single JavaScript file with Angular

For my Angular 8 project, I have successfully imported Bootstrap CSS files into my styles.css file using the following code: /* You can add global styles to this file, and also import other style files */ @import "~bootstrap/dist/css/bootstrap.min.css"; @ ...

Utilizing a PHP Class object in Javascript by accessing its properties within a Javascript function

I'm struggling to access the attributes of an object within a JavaScript function that I created. This object was originally a PHP object that I converted to JSON using json_encode() In my project, there is 1 PHP file and 1 external JS file. In the ...

What is the most efficient method to find a specific value in JSON within SQL when the path is unknown?

Can anyone suggest a quick and efficient method to search for a specific value in a JSON within a SQL table? I need to update this value, which may appear multiple times in the same JSON. update d set d.Content = replace(d.Content, rm.WrongValue , rm. ...

The concept of functions in JavaScript: fact or fiction?

Is there a way to show the message "Yes" or "No" based on the return value of a function without directly using the words true and false, and without utilizing alert? Any suggestions would be greatly appreciated. Thank you. function myFunction { if (Ma ...

Is it feasible to conceal a certain field once the user has chosen another field?

Looking to create an IF statement that will help me establish a specific rule. On a customer portal page, customers can open tickets via a form where they provide information such as "software product" and "environment" from dropdown lists, as well as othe ...