Obtain the count of a two-value array from a Laravel controller and pass it to JavaScript

I need help with a query that calculates the count based on conditions for genders "male" and "female".

$users[] =  User::whereIn('gender',array('male', 'female'))->count()->get();
    return view('/',compact('users[]'));
    

The counts are then displayed in a bar chart.

function drawStacked() {
        var genders[] = {{ $users[] }}
        var data = google.visualization.arrayToDataTable([
            ['Element', '', { role: 'style' }, { role: 'annotation' } ],
            ['Male', '#000', genders[0]],
            ['Female', '#000', genders[1]],
        ]);
    }
    

However, only the count of gender male is being shown.

Answer №1

To achieve the desired outcome, it is necessary to run two separate queries:

$malePopulation = User::where('gender', 'male')->count();
$femalePopulation = User::where('gender', 'female')->count();
return view('/', compact('malePopulation', 'femalePopulation'));

Answer №2

The solution provided by Alexey Mezenin is effective, but I prefer to consolidate it into a single location and return an array that can be displayed in JavaScript. For instance:

genders[0] for male and genders[1] for female

Answer №3

To store Alexey's solution in an array, simply follow these steps:

$totals = [
    'men' => User::where('gender', 'male')->count(),
    'women' => User::where('gender', 'female')->count()
];

return view('/', compact('totals'));

Once stored, you can retrieve the values in your view using the following code:

$totals['men']
// or
$totals['women']

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

Utilizing Jquery's .GET method to retrieve and handle JSON data

In the jQuery snippet below, I am trying to fetch product data from . However, I am facing difficulty in iterating through the loop to access all 30 products along with their details. $.get("https://dummyjson.com/products/1") .done(function ...

When I tried using $.Post with Json in ASP.NET MVC 1.0, I encountered an error indicating that the maximum length had

I encountered the following error message. It appears to be a max length exceeded error when I make a call to an action in a controller using the $.post method. What configuration should I adjust to increase the length restriction? System.InvalidOperatio ...

Error: The property 'match' is undefined and cannot be read by Object.j during rendering in angular-datatables.min.js at line 6

I am currently using angular-datatables.min.js for my data table, but I have encountered an error that I have been unable to resolve. Is there anyone who can provide assistance with this issue? App.controller('DailyTaskListController', ['$s ...

Revive the JavaScript library for handling mouse wheel events

Utilizing the wheel-indicator JavaScript library, I am looking to revert the mouse wheel event back to its original state after it was initially set to preventDefault(). Despite attempting to use indicator.setOptions({preventMouse:"false"}) as suggested b ...

How can you begin using version 4.4.0 of nuxtjs/axios in nuxt.js?

My plan is to incorporate the nuxtjs/axios module into my project. My first step is to install the module using npm: npm install nuxtjs/axios Next, I configure the settings in the nuxt.config.js file: modules: [ ['@nuxtjs/axios', { ba ...

Avoiding metacharacters and utilizing them as a string variable for selection

For example, I have a variable called myid, and its value is "abc xyz". Then, I use a function to escape metacharacters and assign the result to another variable like this: var x = "#"+escapechars(myid);. The evaluated value of x is #abc\\xyz. ...

Error: Unforeseen JSON reply from node

I am a beginner in programming and if my question is unclear, please let me know. I will try to simplify it. Recently, I made a request to a Restful API, using this code snippet const request = require('request'); var myJSONObject = { "call":"L ...

The global class variable encounters an error when trying to assign the value of "socket" to it

Within my class constructor, I am setting up a Socket connection and then storing the socket parameter in a global class variable (this.socket_variable = socket) so that I can access it across all functions in the class. CODE const { Server } = require(&q ...

Is it possible to count the number of days in between and then apply a specific class to each of those days

Here is the code snippet that I am working with: <div class="row"> <div class="test">02/12/2013</div> <div class="test">03/12/2013</div> <div class="test">04/12/2013</div> <div class="test"> ...

Shader in THREE.js only appears when the window is resized

I recently started working with THREE.js and have been experimenting with shaders. Strangely, I've noticed that this particular shader only displays correctly when I resize the window. You can find the code here. Any ideas on why it's behaving th ...

Using Alamofire to retrieve data from a JSON API

I am facing an issue where I am trying to populate a label with text fetched from an API, but it appears that the function responsible for this task is not being called at all. Can someone please review the code snippet below and help identify any potentia ...

Issue with rendering Backbone subview correctly

Today, I delved into the world of website development using backbone.js. Surprisingly, after a whole morning of trying to crack a puzzling problem, I find myself stuck. Let me focus on the crucial bits of code here. Initially, I have a View named Navigat ...

Exploring Ruby on Rails: JSON representation of validation error codes

Currently, I'm developing a Rails web application with a JSON API designed for mobile apps. As an example, the application sends a POST JSON request to example.com/api/orders in order to create an order. {id: 1, order: { product_name: "Pizza", price: ...

Cursor starts to move to the front of the input line after every single letter with a 1 millisecond delay while browsing certain websites, such as the comments section on Youtube

When I type a letter in the field, within 1 millisecond the cursor jumps to the beginning of the line in the typing field, causing text to be typed in reverse. I can only send messages on certain sites, such as YouTube comments and Yandex Translate, for ex ...

Having trouble incorporating autocomplete search results into an HTML table using Jquery, Ajax, and JSP

My current project involves an App that utilizes AJAX with jQuery to communicate with a Spring-boot REST controller. While the app is functional, I am facing difficulty in displaying the search results neatly within HTML tables. https://i.sstatic.net/7sw8 ...

Methods to Maintain Consistent HTML Table Dimensions utilizing DOM

I am facing an issue with shuffling a table that contains images. The table has 4 columns and 2 rows. To shuffle the table, I use the following code: function sortTable() { // Conveniently getting the parent table let table = document.getElementById("i ...

Converting data into a hierarchical structure for a JSON file

Can someone assist me in parsing this specific file for the Gene Ontology (.obo)? I need guidance on how to accomplish this task. I am currently working on a project that involves creating a visualisation in D3. To achieve this, I require a JSON format "t ...

Create HTML content dynamically with JavaScript and then utilize AngularJS to interpret and render it

I am creating an HTML table that looks like this: <table id="#webappname"> <tr ng-repeat="data in d"> <td>1 {{data}}</td> <td>2 hey !</td> </tr> </table> To create this, I am using a ...

Create a time of 00:19:59 using JavaScript

I am attempting to display a countdown timer that starts at 20 minutes in the format (00:20:00) using setInterval. Once the countdown is finished, it should display as (00:00:00), but I am having trouble achieving this. <body onload = "onloadFunc();" ...

How to Override package.json Scripts in NPM

Is it possible to modify package.json scripts without changing the original file? I need to customize the memory allocation for a specific step, but altering the package.json will affect everyone. For example, our current script is: "script": { "dev": ...