Implementing Laravel's functionality for calculating average ratings with the help of jQuery

In my database, I have two tables named Users and ratings. The Users can give ratings to consultants, and the Ratings table structure is as follows:

 User_id | consultant_id | rating
 ---------------------------------      
        1           1        2
 ---------------------------------
        2           1        3
 ---------------------------------
        3           1        1
 ---------------------------------
        4           1        1

This is how the table looks like.

Here is a snippet of my controller code:

public function searchConsultants(Request $request)
{
         $location = $request->get('location');
         $data = Consultant::where('location','LIKE','%'.$location.'%')->with('ratings')->get();
         return response()->json($data);
}

The response I receive from the `searchConsultants` method contains data about the consultants along with their ratings.

[{"id":1,"cunsultant_name":"Manjunath Mj",
     "contact_number":"9035206471",
     "location":"Delhi",
     "department_id":1,09:00:51",

       "ratings":[{
           "id":1,"customer_id":1,"consultant_id":1,"rating":4, 
           "id":2,"customer_id":2,"consultant_id":1,"rating":2, 
           "id":3,"customer_id":3,"consultant_id":1,"rating":1, 
           "id":4,"customer_id":4,"consultant_id":1,"rating":5, 
    }]
}]      

To display this data using Ajax GET method, below is a snippet from my JavaScript file:

$.each(data, function(index) {
   str +="<tr><td>"+data[index].id+"</td>
  <td>"+data[index].cunsultant_name+"</td>
  <td>"+data[index].contact_number+"</td>
  <td>"+data[index].ratings[index].rating_for_manager+"</td><td>"+data[index].location+"</td></tr>";
}); 

Upon clicking the search consultant button, I expect to retrieve details of the consultants along with their average ratings.

Answer №1

To retrieve the average rating, you can modify the query within your Controller's searchConsultants method.

Revise your query as follows (this modification will provide you with the average rating for each consultant that matches the search criteria):

$data = Consultant::select('consultants.*', DB::raw('avg(rating)') )

->where('location','LIKE','%'.$location.'%')

->join('ratings', 'ratings.consultant_id', '=', 'consultants.id')

->groupBy('consultant_id')->get();

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

Troubleshooting Google API PHP offline access issue: "invalid_grant error: Code has already been used"

What is the method to authorize a Google Client indefinitely unless authorization is revoked by the user? I am currently developing an application that requires integration with Google Calendar. Since it needs to function in PHP, I am utilizing the Google ...

Accessing React Context globally using the useContext hook

I'm feeling a bit puzzled about how the useContext hook is intended to function in a "global" state context. Let's take a look at my App.js: import React from 'react'; import Login from './Components/auth/Login'; import &apos ...

How can you divide a single PDF file into multiple pages with the Laravel framework?

I'm currently engaged in a project that requires a PDF splitting feature for a website. Does anyone know how to divide a PDF file into individual pages? I've attempted using www.splitapdf.com for splitting my PDF into separate pages, but now I n ...

Is the [] value always populated in the second DropDownList?

After populating two DropDownList in my View, I encountered an issue with the values not updating as expected: <tr> <td class="info_label">City</td> <td>@Html.DropDownListFor(m=>m.User.City,Model.City,"-- Select ...

document ready function in the Microsoft AJAX client side library

The Microsoft AJAX client-side library contains various functions that imitate the server-side Page Life Cycle and conditions like if (!Page.IsPostBack). I am unsure about which client-side function corresponds to the equivalent server-side method. What is ...

Frequently, cypress encounters difficulty accessing the /auth page and struggles to locate the necessary id or class

When trying to navigate to the /auth path and log in with Cypress, I am using the following code: Cypress.Commands.add('login', (email, password) => { cy.get('.auth').find('.login').should(($login) => { expect($log ...

Having trouble persisting my login status in Selenium using Python

Has anyone experienced issues with logging into Instagram using an automate tab? Previously, I didn't have any problems, but now it seems that Instagram is not allowing users to log in through automation. An error message stating the following appears ...

Troubleshooting the issue of process.nextTick not being recognized in Calgolia places.js

After successfully implementing Algolia's places.js in my Angular 7 project using NPM, I encountered an issue. I have integrated a form where one of the fields should be an input. <form [formGroup]="myForm"> <pre style="color: white; b ...

We were unable to load the resource because the server returned a 404 (Not Found) error. The EnterpriseMaster/BindNatureofAssignment feature is not functioning properly after being published

While the code is working perfectly fine on localhost, as soon as I publish it I encounter an error that prevents the table from loading. EnterpriseMaster/BindNatureofAssignment:1 Failed to load resource: the server responded with a status of 404 (Not ...

What is causing MySQL to strip slashes from the data?

Here is a simple function example: mysqli_query($link, 'update table set field = \'variable text with \" slash\' '); $res = mysqli_query($link, 'select field from table'); $res = mysqli_fetch_array($res); Aft ...

Why won't the infowindow close when I press the close button in the markercluster of Google Maps API v3?

initialize map function initializeMap() { var cluster = []; infoWindow = new google.maps.InfoWindow(); var map = new google.maps.Map(document.getElementById("map"), { cen ...

The initial JavaScript load shared by all users is quite large in the next.js framework

Currently working on a project using the Next.js framework and facing an issue where the First Load JS shared by all pages is quite heavy. I am looking for advice on possible strategies to reduce the weight of the JS file, and also wondering if there ...

What are some effective techniques to optimize this node.js code and eliminate redundancy?

I am currently in the process of setting up a basic template for my demonstration project and writing my first node.js program. The piece of code below is functioning properly for my initial test, but it contains duplicated sections - Getting connection, E ...

Tips for effectively handling databases containing a small volume of data

Hey there! I'm currently working on building a social network using Dreamweaver, with PHP and SQL as my server languages. To host my website, I've decided to go with GoDaddy.com, which offers unlimited MySQL databases, each capped at 1gb. My pla ...

React's connect method is causing issues with my test case

Attempting to create a test case for my jsx file... Took a sample test case from another jsx file... The other file does not have the connect method... But this new file contains the connect method... Believe this is causing issues with my test case... Any ...

Adjust the language code in a URL using JavaScript or Node.js

Within my common header file, there is a navbar that includes a multilanguage dropdown menu. The issue I am facing is that when I select a language from the dropdown, the page translates correctly. However, when I navigate to other pages, the selected lang ...

Improving JSON encoding functions in PHP version 5.2

There appears to be a bug in JSON encode for php 5.2. Is there a way to resolve this issue without updating my PHP version to 5.3+? If so, how can I do it? Thank you I have identified the problem - it was related to an encoding issue with my string. The ...

JavaScript - Reveal a div when a grid item is clicked

I have created a grid with a 5x7 layout using divs. I am trying to achieve a feature similar to the Netflix interface where, upon clicking on a div, a larger div will appear beneath it. This larger div should expand to 100% width of the parent container, p ...

Have you checked the console.log messages?

As a newcomer to web development, I hope you can forgive me if my question sounds a bit naive. I'm curious to know whether it's feasible to capture a value from the browser console and use it as a variable in JavaScript. For instance, when I enco ...

Learn how to retrieve data from the console and display it in HTML using Angular 4

Need help fetching data inside Angular4 HTML from ts variable. Currently only able to retrieve 2 data points outside the loop. Can anyone assist with pulling data inside Angular4? HTML: <tr *ngFor="let accept of accepts"> ...