vendredi 8 septembre 2017

Broadcast retrieved results from DB with accessors to socket.io or javascript

Problem: I cannot retrieve an accessor argument in javascript file in Laravel 5.4

Scenario:

  1. Get data
  2. Modify retrieved data with Accessors
  3. Via Event broadcast to Listeners
  4. Catch a broadcasted event in javascript with socket.io

In App/SomeModel.php I am doing a manipulation over retrieved data by using Eloquent.

Based on priority number, I assign a correct class name for bootstrap styling.

/**
 * Gets corresponding class name based on priority level.
 *
 * @return string
 */
public function getPriorityClassAttribute(): string
{
    switch ($this->priority) {
        default:
            return '';
        case 1:
            return 'info';
        case 2:
            return 'success';
        case 3:
            return 'warning';
        case 4:
            return 'danger';
    }
}

Then I can access $somedata->priority_class everywhere across the application.

But I cannot pass those data to the Listeners in javascript. I don't know how should I add it to the data object.

Here is a var_dump() in my Event broadcaster:

#attributes: array:2 [
"priority" => 2
"id" => 128

]

Why there is no priority_class while it works if I want to $somedata->priority_class ?

Any tips ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire