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

Asked

Viewed 644 times

1

What do I need? I need when a user in the frontend sends a message to the system and the system (Dashboard backend) to receive a real-time notification that is the message just created. I’m doing it like this. In my controller in the store() method of the controller responsible for the Model Contact, it records in the database the contact form of the frontend calling the event Notificacaocontato Thus remaining:

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 don’t know how to register this event in Appserviceprovider How would I do that? Moving on. In my . env 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 decoded it in my Provider array which is in App config app.php Just that the 2 line in my case

 Illuminate\Broadcasting\BroadcastServiceProvider::class,

Right after In my Event itself I did so:

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 have imported the one from push to my Dashboard backend template along with the script that push already provides. That being so: 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 with this code. When I send it, I submit the form to the store() method on the push.com website and it shows that something happens. That my event is called. More pera ai, it was not to appear the Alert in my backend Dashboard?

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

Exit on the console inserir a descrição da imagem aqui

2 answers

2

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

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

1) No registration required Broadcastserviceprovider and yes the Eventserviceprovider.

2) The config/Broadcasting.php file must 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 the Front-End you must bind your client in the created channel and explain the name of the event (shot in Rigger within your action) that the service will listen to.

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.

  • Um. I get it. But let me ask you a few more questions Lorenzo. No num. 3) what is this action you’re talking about where this file is? $options = [ 'cluster' => 'us2', 'Encrypted' => true ]; $Pusher = new Pusher( 'xxx', 'yyy', 'zzz', $options ); That’s in my controller ? That part I missed. And what would that yyy zzz xxx ?

  • Lorenzo, I understand that @Natanmelo calls "Dashboard backend" is an administrative area of the application itself. So it wouldn’t be the other way around like you said. The need remains for the server to send a message to the front end (administrative). Natan, please confirm that’s right.

  • Rightly. When an internet user sends in the contact form to the administrative area I receive there in the administrative area a notification. From user front end -> to aministratriva area (Backend Dashboard) . @bfavaretto

  • I edited the post and I’m showing the output that is giving. More in my view still not appearing anything. Now I did so When I publish an article in my main view appears an alert or whatever saying that was posted a new article @bfavaretto

  • Caramba I solved this po** Putz that complicated thing for me to put to work. More I am very happy.

  • @bfavaretto I understood then. But I was referring to the theory even when I meant that it was the opposite. It was just to clarify that the idea of using a service that uses web sockets is to allow the server to have "autonomy" to communicate with the client without a request from the client (as is the standard of the web architectures). :)

  • Arthur, I’m glad you made it. But to answer your previous question. The action I was referring to was your method that would receive the request, your Controller. And the "xxx", "yyy" and "zzz" were just meant to represent that there should be your credentials hug!

Show 2 more comments

1


Okay. I’m going to show you here how I solved this problem that I was having. Only instead of notifying the frontend to Backend, I did the opposite, from Backend to frontend. Soon I changed the concept I was wanting to do, but the concept is the same. So the idea now is, when I create an article that the frontend is notified that a new article has just arrived.

What I’ve changed is a few parts. In my Event called Notificacaocontato I changed to Notificacaorartigo since I want to notify a new article so the name makes sense. And in this Notification Event I took the channel deprivation and left it as if it were public As it was before:

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

See that it is as Privatechannel. Then I switched to:

return new Channel('notifica-artigo');

so I had access in frontend.

As I was having doubts about whether I was registering events on Appserviceprovider or registering anywhere else, I didn’t 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. Getting 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 way it got pretty cool is just what I was needing. 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 frontend form as I proposed to do in my original post idea.

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.