【问题标题】:Returning an array in onOpen function在 onOpen 函数中返回一个数组
【发布时间】:2019-07-12 08:57:39
【问题描述】:

我目前正在编写一个聊天应用程序。到目前为止,用户可以互相发送消息,我可以将消息存储在我的数据库中。现在我想在我的 onOpen 函数中显示存储在数据库中的消息,当用户打开页面向另一个用户发送消息时。

这就是我的 onOpen 函数的样子:

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();

    }

我想将 $messages 数组返回到我的 privateChat.blade.php 视图中,以便将它们打印出来。

我尝试在我的privateChat.blade.php 中执行return view('privateChat',['messages' => $messages]);@dd($messages),但它说变量未定义。 我还尝试了return $messages 并在我的 onopen js 函数中将它们打印出来,但它不起作用。什么是正确的方法?

【问题讨论】:

    标签: javascript laravel websocket ratchet


    【解决方案1】:

    如您所见,您没有返回任何内容

    所以

    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);
    
    }
    

    如果有什么问题欢迎在下方留言

    【讨论】:

    • 尝试用@dd($viewShareVariables) 打印出来,它给了我一个Undefined variable: viewShareVariables 的错误
    • 我认为您误解了它,您可以尝试 @dd($messages),它被传递到 compact() 并作为 视图助手中的第二个参数
    • 问题是我已经在另一个函数中返回了我的privateChat 视图并将变量传递给它,因此再次返回它不起作用,因为我已经在那个视图中。相反,我尝试将 $messages 数组与其他变量一起传递,它起作用了。
    猜你喜欢
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 2012-04-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    相关资源
    最近更新 更多