Is there a way to transform the json file retrieved from the api into a javascript object using laravel's parsing functionality?

Maybe I should try using json.parse here, but I'm not sure how to go about it.

Userscontroller.php

 function list(){


$clients = Clients::all();

$result["users"]=$clients;


return $result;

Here is the data:

{
"users": [
    {
        "id": 1,
        "fullName": "Deniz",
        "company": "Riskomer",
        "role": "editor",
        "username": "denden",
        "country": "Türkiye",
        "contact": "05355141450",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5bdb4b9b9bab7a7baede795b2b8b4bcb9fbb6bab8">[email protected]</a>",
        "currentPlan": "Enterprise",
        "status": "inactive",
        "avatar": ""
    },
   

I want it to look like this. Essentially, I need to convert the JSON object to a JavaScript object as shown below. How can I achieve this with Laravel?

users: [
{
  id: 1,
  fullName: 'Galen Slixby',
  company: 'Yotz PVT LTD',
  role: 'editor',
  username: 'gslixby0',
  country: 'El Salvador',
  contact: '(479) 232-9151',
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5631253a3f2e342f661637343578383322783723">[email protected]</a>',
  currentPlan: 'enterprise',
  status: 'inactive',
  avatar: '',
},

Answer №1

If you want to add a parameter to each item in a list, using the each() and setAttribute() method is recommended.

$data = \App\Models\Items::all()
    ->each(function (\App\Models\Items $item) {
        return $item->setAttribute('newParam', 'example');
    });

In your javascript code, remember to parse the JSON data into a JavaScript object by using JSON.parse().

JSON.parse('{!! $data !!}')

Note: When echoing out the $data, use {!! !!} instead of {{ }} to avoid escaping special characters.

Answer №2

fetch all clients data

returns an array of objects containing client information

[{client1,client2,client3...}]

if you want to give this array a name, you can do so like this:

$clientsArray = array('clients' => Clients::all());
return $clientsArray;

the output will then look like this:

clients: [{client1,client2,client3...}]

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

Applying style changes to the height on scroll event in Javascript for Chrome, Firefox, and Internet Explorer

I am working on triggering an event when scrolling to a specific height. I have code that successfully adds a style in Chrome, but it is not functioning properly in IE. Can anyone provide assistance? myID = document.getElementById("subnav"); var mySc ...

breaking up string values in Node.js

I am currently facing an issue with splitting values from an array. Here is how the array looks: [ 'xs', 'small', 'medium' ] I am trying to rearrange them to display like this in my database: xs small medium Here is what I ...

Eliminate the primary JSON keys that exist in the second JSON dataset

I need to utilize jq in order to eliminate keys from the initial file that are present in the second file. Here is what we have: a.json: {"a": 1, "b": 2} b.json: {"b": true} The finalized content of diff.json should be lik ...

Obtain a variety of selections for multiple selects and individually incorporate them into a standard select menu

Is there a way to select multiple options from a list and add them to another list without losing any selections? Currently, when I add two selected options, they combine into one in the target list. Check out this JSFIDDLE EXAMPLE for reference. Here is ...

What steps can I take to allow a third-party JavaScript to access my TypeScript object?

I am working on an Angular application and I have a requirement to develop an API for a third-party JavaScript that will be injected dynamically. public class MyApi{ public callSomeFunction():void{...} public getSomeValue():any {...} } var publicA ...

Gathering data from a webpage containing a table populated by JavaScript

I need to extract data from this webpage in order to process generation data with a parser later. The issue I'm facing is that the table on the page is populated by multiple scripts making requests to another server. When using Beautiful Soup to scra ...

Is this jQuery script not functioning properly?

I came across this code on jsfiddle, and I really want to incorporate it into my PHP file. However, when I tried to do so, it didn't work even though I simply copied and pasted the code without making any changes. Here is my code: <!DOCTYPE html& ...

Looking to incorporate new values without replacing them in react.js and mongoDB

function getFilterQuery() { const completedWorkState = WorkflowStates.findOne({title: 'Completed'}); const inProgressWorkState = WorkflowStates.findOne({title: 'In Progress'}); const identifiedWorkState = WorkflowStates.findOne ...

Even though the Web API has CORS Policy set up, it is still being blocked

I am currently working on an ASP.NET Core Angular application. I have added an API Controller in the Core app and am attempting to make an API call from the Angular app. The Core app is hosted on port 58181 and the Angular app on port 44337. However, when ...

How do I assign a default value to an optional parameter in a derived class in Typescript?

One of my classes is called ClientBase: export class ClientBase { constructor(private uri: string, private httpClient: HttpClient) { } // Contains Various Methods } I have multiple subclasses that are derived from the ClientBase For instance: @I ...

Tips for adjusting the value of a textbox up and down

I am facing an issue with my booking flight form that is supposed to take input from users regarding the number of travelers. I have three textboxes for Adult, Children, and Infants respectively, along with a main textbox to display the final result. Howev ...

Issue with transferring variables between functions in JSON and Jquery

I'm currently working on a script that involves retrieving the variable hf using getJSON $.getJSON('../scripts/json.php', function(json) { var user_function = json.hf; }); In addition to this, I have developed an auto_refresh feature ...

What is the best way to adjust menu alignment for big screens?

Is there a way to set the alignment of a dropdown menu to the right specifically for large screens? <div class="btn-group"> <button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expande ...

Adjust the size of a div by clicking a button using Javascript

<script type="text/javascript"> var btn = document.getElementById("btn"); var panel = document.getElementById("panel"); var btn2 = document.getElementById("btn2"); function expandPanel() { btn.style.display="none"; panel.style="overflow:hidd ...

Changing a Javascript Array into a string with delimiters

I have a Javascript array of strings that contain alphanumeric values such as A12, B50, C105. My goal is to convert this array into a pipe delimited string format like: A12|B50|C105... Can anyone guide me on how to achieve this? I am specifically working ...

Retrieving a Promise's value for an HTML Element

Hello, I'm new to working with React and JavaScript and could use some assistance. I have a function that returns a Promise that includes an interface. My goal is to access a variable in the interface and use it within <dl><dt>{//string va ...

Creating a transcluding element directive in AngularJS that retains attribute directives and allows for the addition of new ones

I've been grappling with this problem for the past two days. It seems like it should have a simpler solution. Issue Description The objective is to develop a directive that can be used in the following manner: <my-directive ng-something="somethi ...

Switch the scroll direction in the middle of the page and then switch it back

Yesterday, while browsing online, I stumbled upon this website and was amazed by the unique scroll direction change from vertical to horizontal mid-page. I'm curious about how they managed to achieve that effect. Does anyone have insight into the pro ...

Looking for assistance with REGEXP to handle a 404 path rendering issue

I am attempting to utilize REGEXP in order to display a 404 page within a react app based on the path, but I am struggling to make it work. This is the specific REGEXP pattern I am trying to achieve: The entire path should not be '/' and should ...

What is the most effective way to transmit a sizeable JSON file to a server?

In my web.config file, I set the maxrequestlength to 10MB. However, there is a feature in my system that allows clients to import a .csv file that can potentially be larger than 10MB. As a result, I am looking for an efficient way to send a large json file ...