Real-Time How it works. Well I'm having problems with my tests Laravel 5.4

1

What do I need? I need when a user in the frontend sends a message to the system and the dashboard backend receives a real-time notification that the message has just been created. I'm doing this. In my controller in the store () method of the controller responsible for the Model Contact, it writes in the database the contact of the frontend form calling the NotificationContact event Staying like this:

public function store(Request $request){
  //dados do formulário contato 
  $result = Contato::create($request->all());
   //Evento a ser chamado
  \Event::fire(new NotificacaoContato($result)); 
}

Now I'm not sure how to register this event in AppServiceProvider How would I do that? Continuing. In my .env I set the environment variables as follows:

BROADCAST_DRIVER=pusher
PUSHER_APP_ID="Meu ID"
PUSHER_APP_KEY="Minha chave que eu peguei la no site do push.com "
PUSHER_APP_SECRET="Chave secreta pega no push.com"

Then I uncommented it in my Provider array which is in App \ config \ app.php Just the 2 line in my case

 Illuminate\Broadcasting\BroadcastServiceProvider::class,

Soon after In my event itself I did it this way:

class NotificacaoContato implements ShouldBroadcast
 {
use Dispatchable, InteractsWithSockets, SerializesModels;

/**
 * Create a new event instance.
 *
 * @return void
 */
public $contato;
public function __construct($contato)
{
    $this->contato = $contato;
}

/**
 * Get the channels the event should broadcast on.
 *
 * @return Channel|array
 */
public function broadcastOn()
{
    return new PrivateChannel('notificacao-contato');
}
}

Now in my View I put the push import to my dashboard backend template along with the script that the push already makes available. Staying like this: View (dashboard backend Template)                      

// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;

var pusher = new Pusher('aqui vai a minha chave o mesmo do .env', {
    cluster: 'us2',
    encrypted: true
});

var channel = pusher.subscribe('notificacao-contato');
channel.bind('App\Event\NotificacaoContato', function(data) {
    alert('Uma Conatato foi enviado');
});
</script>

What happens to this code. When I submit I submit the form to the store () method on the push.com website it shows that something happens. That my event is called. More then, was not there an alert on my dashboard backend?

Consoleoutput

    
asked by anonymous 12.10.2017 / 02:25

2 answers

1

Well. I'll show you here how I solved this problem I was having. Only instead of making the notification from the frontend to the backend, I did the opposite, from the backend to the frontend. So I changed the concept I wanted to do, but the concept is the same. So the idea now is, when I create an article that the frontend is notified I just got a new article.

What I've changed is in parts. In my my event called NotificationContact I changed to NotificationProject since I want to notify a new article so the name makes sense. And in this Notification Event I stripped off the channel and left it as if it were public. In this way: As before:

public function broadcastOn()
{
 return new PrivateChannel('notificacao-contato');
}

See that it is PrivateChannel. Then I changed to:

return new Channel('notifica-artigo');

So I had access on the frontend.

As I was having doubts about whether I was registering the events in the AppServiceProvider or registering anywhere else, I did not need to. Because I'm calling the event directly. Already in my frontend I created a div putting the css to leave as display: none. Staying like this:

<div class="row">
<div class="col-md-12 alert alert-success artigo" id="msg" style="display: none"></div>

<script>

// Enable pusher logging - don't include this in production
Pusher.logToConsole = false;

var pusher = new Pusher('Aqui vai a minha chave', {
    cluster: 'us2',
    encrypted: true
});

var channel = pusher.subscribe('notifica-artigo');
channel.bind('App\Events\NotificacaoArtigo', function(data) {
   //aqui add o texto na div
   $('.artigo').text('O artigo (' + data.artigo.titulo + ') acaba de ser criado');
    //aqui eu mostro a div que esta escondida pelo display:none 
    $('.artigo').show();
    //aqui eu escondo a div depois de alguns segundos. 
    $(document).ready(function () {
        setTimeout(function () {
            $('#msg').fadeOut(15000);
        }, 10000);
    });
});

So that's how cool it is, that's just what I needed. Very grateful to those who helped me to have a north. Seeing what I've done, I'll do the reverse. receiving a notification in the administrative area coming from a form of the frontend as I proposed to do in my original idea of the post.

    
12.10.2017 / 08:05
2

In reality the idea of Real-Time service is the exact opposite.

The Laravel broadcast service enables your application to perform server-side requests to the client side through the use of services that implement web sockets, such as Pusher in this case.

1) You do not need to register the BroadcastServiceProvider provider, but the EventServiceProvider.

2) The config / broadcasting.php file should be created with the following structure:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Broadcaster
    |--------------------------------------------------------------------------
    |
    | This option controls the default broadcaster that will be used by the
    | framework when an event needs to be broadcast. You may set this to
    | any of the connections defined in the "connections" array below.
    |
    | Supported: "pusher", "redis", "log", "null"
    |
    */

    'default' => env('BROADCAST_DRIVER', 'pusher'),

    /*
    |--------------------------------------------------------------------------
    | Broadcast Connections
    |--------------------------------------------------------------------------
    |
    | Here you may define all of the broadcast connections that will be used
    | to broadcast events to other systems or over websockets. Samples of
    | each available type of connection are provided inside this array.
    |
    */

    'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_KEY'),
            'secret' => env('PUSHER_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
        ],
    ],
];
?>

3) The action that triggers the event for the service must instantiate a Pusher object and call the trigger method.

For example:

$options = [
    'cluster' => 'us2',
    'encrypted' => true
];

$pusher = new Pusher(
    'xxx',
    'yyy',
    'zzz',
    $options
);

$pusher->trigger('notificacao-contato', 'Nome_Para_o_Evento', ['msg' => ':)']);

4) In Front End you must bind your client to the created channel and specify the name of the event (triggered in the trigger within your action) that the service will be listening.

Example:

var pusher = new Pusher('xxxx', {
    cluster: 'us2',
    namespace: false,
    encrypted: true
});

var channel = pusher.subscribe('notificacao-contato');

channel.bind("Nome_Para_o_Evento", function(data) {
    console.log(data);
});

I hope it helps!

Hugs.

    
12.10.2017 / 03:34