Laravel5.8推杆无法正常工作。无法收到

时间:2019-07-17 05:59:52

标签: php laravel vue.js laravel-5 pusher

我正在创建实时聊天应用程序。 我已经在laravel和vue.js项目中设置了pusher。

但是它不起作用。虽然我在控制台中没有任何错误。 另外,“网络”标签中没有错误。

我需要创建Messenger应用,所以我需要一个实时聊天功能。 现在,我可以推送用户的评论,但是在其他用户的窗口中,什么都没有显示。

但是确实如此,一旦刷新页面。我认为我的pusher设置有问题,因为在pusher调试控制台中,不会执行任何会话。

这是我的代码。 .env

BROADCAST_DRIVER=pusher
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

PUSHER_APP_ID=my id
PUSHER_APP_KEY=my app key
PUSHER_APP_SECRET= my secret key
PUSHER_APP_CLUSTER=mt1

broadcasting.php

'pusher' => [
            'driver' => 'pusher',
            'key' => env('my key'),
            'secret' => env('my secret key'),
            'app_id' => env('my id'),
            'options' => [
                'cluster' => 'ap3',
                'encrypted' => true,
            ],

BroadcastServiceProvider.php

Broadcast::routes(['middleware' => ['auth:api']]);
        require base_path('routes/channels.php');

bootstrap.js

import Echo from 'laravel-echo'

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'my key',
    cluster: 'ap3',
    encrypted: true
});

NewMessage.php

use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewMessage implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $message;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Message $message)
    {
        $this->message = $message;
    }
    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('messages.' . $this->message->to);
    }
    public function broadcastWith()
    {
        $this->message->load('fromContact');
        return ["message" => $this->message];
    }
}

routes / channel.php

use Illuminate\Support\Facades\Broadcast;

ContactsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Message;

class ContactsController extends Controller
{
    public function get() {
        $contacts = User::where('id', '!=', auth()->id())->get();//全部のcontactをjson経由でgetする

        return response()->json($contacts);    
    }

    public function getMessagesFor($id) {
        $messages = Message::where('from', $id)->orWhere('to', $id)->get();
        return response() -> json($messages);
    }

    public function send(Request $request) {
        $message = Message::create([
            'from' => auth()->id(),
            'to' => $request->contact_id,
            'text' => $request->text
        ]);



        return response()->json($message);
    }
}

这是我尝试过的。

根据laravel文档运行所有命令。

php artisan chache:clear 并再次运行服务器。

运行 php artisan queue:work 在命令终端中

3 个答案:

答案 0 :(得分:0)

您写了

fetchStock() {
  const API_KEY = 'api key goes here';
  let TimeInterval = '60min';
  let StockSymbol = 'AMZN';
  let API_Call = `https://www.alphavantage.co/queryfunction=TIME_SERIES_INTRADAY&symbol=${StockSymbol}&interval=${TimeInterval}&outputsize=compact&apikey=${API_KEY}`;

  let stockHistoryDatabase = {};
  let stockHistoryDatabaseString;

  fetch(API_Call)
    .then(response => response.json())
    .then(data => {
      for (var key in data['Time Series (60min)']) {
        var epochKeyTime = new Date(key);
        epochKeyTime = epochKeyTime.getTime();
        stockHistoryDatabase[epochKeyTime] = data['Time Series (60min)'][key]['1. open'];
      }
    this.setState({stockInfo: stockHistoryDatabase}) 
    //Set your state here.

    stockHistoryDatabaseString = JSON.stringify(stockHistoryDatabase);
  }
  );

在您的应用程序中收听

答案 1 :(得分:0)

我更改了pusher应用程序名称,然后在pusher dubug控制台中工作了。 debug console

但是仍然无法正常工作。

我很高兴有人给我解决方案...

这是我的前端代码。 MessagesComposer.vue

    <template>
        <div class="composer">
            <textarea v-model="message" @keydown.enter="send" placeholder="Message..."></textarea>
        </div>
    </template>

    <script>
    export default {
        data() {
            return {
                message: ''
            }
        },
        methods: {
            send(e) {
                e.preventDefault();


                if(this.message == '') {
                    return;
                }
            this.$emit('send', this.message);
            this.message = '';
        }
    }
    }


    </script>

MessagesFeed.vue

    <template>
        <div class="feed" ref="feed">
            <ul v-if="contact">
                <li v-for="message in messages" :class="`message${message.to == contact.id ? ' sent' : ' received'}`"
                :key="message.id">
                    <div class="text">
                        {{ message.text }}
                    </div>
                </li>

            </ul>

        </div>
    </template>

    <script>
    export default {
    created(){
    var userId =1;  //get the id from meta tag 

window.Echo.private(''messages.'+userId).listen('NewMessage',(m)=>{
console.log(m)
})
},
        props: {
            contact: {
                type: Object,
            },
            messages: {
                type: Array,
                required: true
            }
        },
        methods: {
            scrollToBottom() {
                setTimeout(()=>{
                    this.$refs.feed.scrollTop = this.$refs.feed.scrollHeight - this.$refs.feed.clientHeight;

                }, 50); 
            }
        },
        watch: {
            contact(contact) {
                this.scrollToBottom();
            },
            messages(messages) {
                this.scrollToBottom();
            }
        }
    }
    </script>

答案 2 :(得分:0)

在send()函数中,您应该编写 broadcast(new NewMessage($message)); 广播消息。