Sending back an array within the onOpen function

I am currently in the process of developing a chat application. At this stage, users are able to send messages to each other and I have successfully stored these messages in my database. Now, my objective is to display the stored messages from the database when the user opens up the page to engage in conversation with another user.

Below is an example of what my onOpen function entails:

public function onOpen(ConnectionInterface $conn)
    {

        $query =  $conn->httpRequest->getUri()->getQuery();

        preg_match_all('!\d+!', $query, $matches);

        $my_id = $matches[0][0];

        $friend_id = $matches[0][1];

        $conn->resourceId = $my_id;

        $this->users[$conn->resourceId] = $conn;

        $messages = Private_message::where([

            ['user1',$my_id],
            ['user2',$friend_id]

        ])->orWhere([

            ['user1',$friend_id],
            ['user2',$my_id]

        ])->get()->toArray();

    }

My goal is to pass the $messages array to my privateChat.blade.php view for rendering purposes.

I attempted methods such as

return view('privateChat',['messages' => $messages]);
and @dd($messages) within my privateChat.blade.php, but encountered an error indicating that the variable was undefined. I also experimented with using return $messages and displaying them in my onOpen JavaScript function, without success. Can anyone advise on the correct approach to accomplish this?

Answer №1

It appears that there is a problem with returning data back to the view.

Here is a sample code snippet:

public function onOpen(ConnectionInterface $conn)
{

    $query =  $conn->httpRequest->getUri()->getQuery();

    preg_match_all('!\d+!', $query, $matches);

    $my_id = $matches[0][0];

    $friend_id = $matches[0][1];

    $conn->resourceId = $my_id;

    $this->users[$conn->resourceId] = $conn;

    $messages = Private_message::where([

        ['user1',$my_id],
        ['user2',$friend_id]

    ])->orWhere([

        ['user1',$friend_id],
        ['user2',$my_id]

    ])->get()->toArray();

   $viewShareVariables = compact('messages');

   return view('privateChat',$viewShareVariables);

}

If you encounter any issues, please feel free to leave a comment below for assistance.

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

Surprising outcome of Vue

As a newcomer to vue.js, I am struggling with a side effect issue in a computed property. The unexpected side effect error is popping up when running the code below, and ESlint is pointing it out in the console. I understand the concept of side effects, bu ...

Unlocking React Event Handlers using Puppeteer

I'm struggling to fully comprehend my request, and I'm seeking clarification. I am currently working on scraping a website using Puppeteer in NodeJS. So far, I have managed to select the necessary element and access its properties. However, I am ...

Existing key fails to meet foreign key constraint

We have encountered an issue in our current Laravel project while trying to insert a new record into our MySQL database. The process involves creating a new company along with users associated with that company. Strangely, we are facing a foreign key const ...

The POST request encountered an error with status code 500 while being processed by the Express.js framework in the IncomingMessage

My current challenge involves creating a HTTP request for a CRUD application using JS. The aim is to add a new user account record to the Logins database. However, every time I attempt this request, it results in a 500 error: To test this, I have written ...

Enhancing User Experience with Real-Time Control Updates using ASP.Net and Bootstrap

I am struggling to figure out how to update bootstrap controls with ASP.Net. Here is the code I am working with: @{ Layout = null; } <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width ...

Form that adjusts input fields according to the selected input value

I am in need of creating a dynamic web form where users can select a category and based on their selection, new input fields will appear. I believe this involves using JavaScript, but my searches on GitHub and Stack Overflow have not yielded a suitable sol ...

Showcasing Information Using AngularJS from a Json Array

My goal is to present data from a JSON array in a table using the code below. However, all the data is currently being shown in one row instead of each record appearing on separate rows with alternating colors - grey for even rows and white for odd rows. I ...

The Express app.post endpoint is not acknowledging incoming POST requests from Postman

I am facing an issue where my POST request using Postman to my express app is timing out. Here is the request: https://i.sstatic.net/UfL07.png And here is the app: import express from 'express' import bodyParser from 'body-parser' i ...

Next.js experiencing development server compile errors and broken page routing in production builds

Howdy everyone! I'm currently working on an app using Next.js. Every time I make a change, the server automatically compiles with the updates, but unfortunately, the pages often fail to render properly. Sometimes it takes several minutes for them to l ...

Uninitialized Array Member in Angular 8

Can anyone explain why the code snippet below is printing "undefined"? I have created several objects and intended to display the corresponding images, but after iterating through them using ngfor, nothing appeared. To investigate, I logged the array and ...

Designing a photo frame slider for a unique touch

My skills in javascript and jQuery are limited, but I am looking to create a customizable slider. While exploring options like Flexslider (), I found it challenging to meet the following specifications: Eliminate color gaps between thumbnails Enable thu ...

What is the best way to connect a relative CSS stylesheet to a master page?

My Java application generates several HTML pages, organized in different directories: html_pages/ | ----> landin_page.html html_pages/details | ----> index1.html html_pages/more_details | ----> index2.html html_pages/css | ...

AngularJS does not support the use of $(this) syntax

I have encountered an issue while developing a Chrome extension using AngularJS. I would like to add buttons to my popup page, and I want the ancestor node to disappear when a button is clicked. Here is the code snippet: in popup.html <div class="dea ...

The casperjs evaluate function isn't able to provide me with the necessary data I

Having trouble getting my function to return data correctly. I am trying to retrieve the value of this input box. <input type="text" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b6e736a667b6764646025686466">[em ...

The task "grunt-karma.js" is currently being loaded, but unfortunately an error has occurred: SyntaxError - An unexpected identifier was found

Encountering an issue when loading "grunt-karma.js" tasks while all other tasks are loading correctly. This problem started to occur after updating several dependencies, including grunt-karma and karma. Here is the section from my package.json: "grunt-ka ...

Obtain the total number of result entries

I'm working on a project involving JS and PHP. My goal is to call a PHP file using Ajax and have it return the count of result lines. I use echo for this: $connection = new PDO($source, $user); $query = "SELECT * FROM scores WHERE username = '" ...

When the window size is reduced, the navigation vanishes

Whenever I resize the window, the navigation bar disappears. Here is the image of the page before resizing the window https://i.sstatic.net/UiRB9.png Below is the image after resizing the window https://i.sstatic.net/X00d2.png Displayed below is the cod ...

Issue with Magento: Unable to execute dataflow profiles due to Ajax Error (Uncaught TypeError: e is not a function)

Whenever I try to execute a dataflow profile in Magento, the following series of events unfold: The CSV file is uploaded successfully X rows are found A message displays: Starting ... :: saveRow (handler-method) However, a JavaScript error interrupts th ...

Having trouble getting my Leaflet map to display even after meticulously following the quick-start guide

I am experiencing an issue where the map is not displaying at all, leaving a blank space where it should be. Despite following Leaflet's quick-start guide, I have been unable to determine the cause of this problem. Here is the code that I currently h ...

What methods do certain API services use to accept Authorization headers from any source?

Payment processing platforms like Stripe and Square provide the capability to include your API key in an Authorization header as a Bearer token. However, my understanding is that allowing credentials, such as the Authorization header, from all origins is ...