hi i have this js code
var pusher = new Pusher('my pusher key', {
cluster: 'ap2'
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data)
{
console.log(data);
});
and this is my laravel code
protected $pos_invoice;
public function __construct($pos_invoice)
{
$this->pos_invoice = $pos_invoice;
}
public function broadcastOn()
{
return new Channel('my-channel');
}
public function broadcastAs()
{
return 'my-event';
}
and this is the call code
return event( new \App\Events\New_pos_online_order_event('aa'));
now the code
channel.bind('my-event', function(data)
{
console.log(data);
});
always return [] on console so i tried this
public function broadcastAs()
{
return 'my-event.'.$this->pos_invoice;
}
and this
public function broadcastOn()
{
return new Channel('my-channel'.'asdfasdf');
}
when i change anything on
public function broadcastOn()
{
return 'my-channel';
}
public function broadcastAs()
{
return 'my-event';
}
the code not working and not returning anything on console
so how can i pass parameter on pusher and laravel with js
thanks ..
You need to define the function broadcastWith
**
* Get the data to broadcast.
*
* #return array
*/
public function broadcastWith()
{
return ['pos_invoice' => $this->pos_invoice];
}
You will receive the array in the data of the bind function
Related
I am trying to pass some values as array on jobExport() collection and am getting an error Call to a member function jobsExport() on array. I understand that the collection need to populatet with modal collection value, but am trying to export multiple record(only record i select) from table , and to make this happend i thing i need to pass value as array from control to modal method, i have searched a loot to find a solution for this but i dont find anythin yet. Here is what i have done
Route
Route::any('export/jobs/{jobs}', [JobController::class, 'export']);
Pass data from vue to laravel
watch: {
selected: function(){
this.url = '/export/jobs/' + this.selected;
}
},
// After sending request on backend route will look like this
http://127.0.0.1:8000/export/jobs/1,2,4
Laravel controller
public function export($jobs)
{
return Excel::download(new JobsExport($jobs), 'jobs.xlsx');
}
Model Method
public function jobsExport()
{
return Job::with('templates', 'teams')
->whereHas('templates', function ($q) {
$q->where('id', $this->id);
})
->get();
}
JobExport
class JobsExport implements WithStyles, FromCollection, WithMapping, WithHeadings
{
use Exportable;
private $jobs;
public function __construct($jobs)
{
$this->jobs = $jobs;
}
public function collection()
{
return $this->jobs->jobsExport();
}
public function map($jobsExport): array
{
// dd($jobsExport->templates->first()->template_name);
return [
$jobsExport->id,
$jobsExport->templates->implode('template_name', ', '),
$jobsExport->job_completed,
];
}
/**
* #return \Illuminate\Support\Collection
*/
public function headings():array
{
return[
'Id',
'Template',
'Completed',
];
}
}
Is the $jobs an id? If so, make it $jobId
public function export($jobId)
{
// assuming you have Job model which holds the jobs table
$jobs = Job::where('id', $jobId)->get();
return Excel::download(new JobsExport($jobs), 'jobs.xlsx');
}
and in your export class
class JobsExport implements WithStyles, FromCollection, WithMapping, WithHeadings
{
use Exportable;
private $jobs;
public function __construct($jobs)
{
$this->jobs = $jobs;
}
public function collection()
{
// change this
//return $this->jobs->jobsExport();
// to
return $this->jobs;
}
public function map($jobsExport): array
{
// dd($jobsExport->templates->first()->template_name);
return [
$jobsExport->id,
$jobsExport->templates->implode('template_name', ', '),
$jobsExport->job_completed,
];
}
/**
* #return \Illuminate\Support\Collection
*/
public function headings():array
{
return[
'Id',
'Template',
'Completed',
];
}
}
I want to update the list of users with pusher.
When I submit the console shows this error:
enter image description here
I also get Uncaught refering to pusher.js
The pusher.js cointains code for pusher and it is placed in the footer:
let teamChannel = pusher.subscribe('team-list');
teamChannel.bind('updated-team', function(data) {
app.team.push(JSON.stringify(data));
});
My event:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewParticipant implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $team;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($team)
{
$this->team = $team;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|arrays
*/
public function broadcastOn()
{
return new Channel('team-list');
}
public function broadcastAs()
{
return 'updated-team';
}
}
js from my Vue component:
<script>
export default {
data() {
return {
team: [],
}
},
created() {
this.fetchPlayer();
this.listenForChanges();
},
methods: {
fetchPlayer() {
console.log('test');
},
listenForChanges() {
window.Echo.channel('team-list')
.listen('updated-team', (e) => {
console.log("echo is working");
console.log("e is " + e);
})
}
},
computed: {
teamList() {
return this.team;
}
}
}
</script>
My controller has this function:
protected function addPlayer($event, Request $request) {
$profile = auth()->user()->profile;
$profile->participate()->syncWithoutDetaching([$event->id], false);
$team = $event->participants()->get();
event(new NewParticipant($team));
return redirect()->route('event.show', [ 'event' => $event ]);
}
Update: I've moved my pusher code to app.js but the app is still undefined:
const app = new Vue({
el: '#app',
});
let body = document.querySelector("body");
if(body.classList.contains('gruppo-app')) {
Pusher.logToConsole = true;
var pusher = new Pusher('mykey', {
cluster: 'myclutes'
});
let teamChannel = pusher.subscribe('team-list');
teamChannel.bind('updated-team', function(data) {
app.team.push(JSON.stringify(data));
});
}
Update:
The connection with the Pusher is not needed if the Laravel Echo is used.
I focuesd on Echo and I've deleted the this block:
let body = document.querySelector("body");
if(body.classList.contains('gruppo-app')) {
Pusher.logToConsole = true;
var pusher = new Pusher('mykey', {
cluster: 'myclutes'
});
let teamChannel = pusher.subscribe('team-list');
teamChannel.bind('updated-team', function(data) {
app.team.push(JSON.stringify(data));
});
}
To connect Echo correctly the dot . has to be added to the listen function like this:
window.Echo.channel('team-list')
.listen('.updated-team', (e) => {
console.log("echo is working");
console.log("e is " + e);
})
Now the Pusher is working correctly.
I have have the following lib.jslib file
mergeInto(LibraryManager.library, {
IsGuestUser: function (objectName, objectMethodName) {
gamesmart.user.isGuest(function (result) {
console.log(Pointer_stringify(objectName), Pointer_stringify(objectMethodName), result);
gameSmartGameInstance.SendMessage(Pointer_stringify(objectName), Pointer_stringify(objectMethodName), result);
});
}
});
Which gets called from here:
namespace GameSmart {
public class User : API {
[DllImport("__Internal")]
public static extern void IsGuestUser(string objectName, string objectMethodName);
public static void IsGuest(string objectName, string objectMethodName) {
IsGuestUser(objectName, objectMethodName);
}
}
}
And is initiated like so:
public class Test : MonoBehaviour {
void Start() {
GameSmart.User.IsGuest("GameSmart", "OnIsGuest");
}
}
As seen above I pass GameSmart and OnIsGuest to the JavaScript, and when it gets to the JavaScript I call Pointer_stringify() on both of the values.
When converted and logged, I get the following output: 0Zހ𐀀 and ﳀ� I should have gotten GameSmart and OnIsGuest back but I didn't what is causing this to happen?
So the fix for this was to move Pointer_stringify outside of the anonymous function so It looks like this:
mergeInto(LibraryManager.library, {
IsGuestUser: function (objectName, objectMethodName) {
var jsObjectName = Pointer_stringify(objectName);
var jsObjectMethodName = Pointer_stringify(objectMethodName);
gamesmart.user.isGuest(function (result) {
gameSmartGameInstance.SendMessage(jsObjectName, jsObjectMethodName, result);
});
}
});
I have the following BreezeController
[BreezeController]
public class BreezeController : ApiController
{
readonly EFContextProvider<MyContext> _ContextProvider = new EFContextProvider<MyContext>();
[HttpGet]
public string Metadata()
{
return _ContextProvider.Metadata();
}
....other controllers exposing model types....
[HttpGet]
public IQueryable<Size> Sizes()
{
return _ContextProvider.Context.Sizes;
}
}
which I access from the client from my DataContext.js with this
var getSizes = function (sizesObservable, modelId) {
var query = entityQuery.from('Sizes').where('ID', '==', modelId)
.orderBy('sortOrder').orderBy('size').orderBy('enteredDate');
return manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
function querySucceeded(data) {
if (sizesObservable) {
var intialValues = { size: ' Select a Size', sizeID: breeze.core.getUuid(), modelID: modelId };
createNullo(entityNames.size, 'Size', intialValues);
sizesObservable(data.results);
}
log('Retrieved [Sizes] from remote data source', data, false);
}
};
All of this works just fine. I would like to add another route to my controller that has some specialized filtering done on the server.
[HttpGet]
public IQueryable<Size> GetUniqueSizes()
{
return //custom filtering logic here.
}
with the following javascript in my DataContext.js
var getUniqueSizes = function (sizesObservable, modelId) {
var query = entityQuery.from('GetUniqueSizes').where('modelID', '==', modelId).where('Approved', '==', 'True')
.orderBy('sortOrder').orderBy('size').orderBy('enteredDate');
return manager.executeQuery(query)
.then(querySucceeded);
function querySucceeded(data) {
if (sizesObservable) {
var intialValues = { size: ' Select a Size', sizeID: breeze.core.getUuid(), modelID: modelId };
createNullo(entityNames.size, 'Size', intialValues);
sizesObservable(data.results);
}
log('Retrieved [Sizes] from remote data source', data, false);
}
};
but when I do this I get the following error on the client
TypeError: Cannot read property 'toODataFragment' …localhost:63144/scripts/breeze.debug.js:12728:23)
Why is this route not working?
try changing the multiple orderBy statements to a multiple property sort.
.orderBy('sortOrder,size,enteredDate')
likewise, you might have better luck if you combine the where clauses.
I'm trying to make my call to the server with BreezeJS but can't get it to work. It says tblMovie is not recognized. I can't find the problem :S
When I want to add a new movie it says so.
show.js
self.viewAddMovieModal = function () {
self.app.showModal(new self.addmovie()).then(function (result) {
if (result != undefined) {
var movie = dataservice.createMovie({
Title: result[0].title,
Director: result[0].director
});
if (movie.entityAspect.validateEntity()) {
self.movies.push(new movie(result[0].title, result[0].director));
dataservice.saveChanges();
} else {
alert("Error");
}
}
});
};
My dataservice.js layer
/// <reference path="../../Scripts/breeze.debug.js"/>
define(["require"], function (require) {
var Dataservice = (function () {
function Dataservice(service) {
this.serviceName = '';
this._isSaving = false;
this.serviceName = service;
this.Manager = new breeze.EntityManager(this.serviceName);
this.EntityQuery = new breeze.EntityQuery();
}
Dataservice.prototype.getAllMovies = function () {
this.EntityQuery = breeze.EntityQuery.from("AllMovies");
return this.Manager.executeQuery(this.EntityQuery);
};
Dataservice.prototype.createMovie = function (initialValues) {
return this.Manager.createEntity('tblMovies', initialValues); //THis is where it goes wrong :(
};
Dataservice.prototype.saveChanges = function (suppressLogIfNothingToSave) {
if (this.Manager.hasChanges()) {
if (this._isSaving) {
setTimeout(this.saveChanges, 50);
return;
}
this.Manager.saveChanges().then(this.saveSucceeded).fail(this.saveFailed).fin(this.saveFinished);
} else if (!suppressLogIfNothingToSave) {
}
};
Dataservice.prototype.saveSucceeded = function (saveResult) {
this._isSaving = false;
};
Dataservice.prototype.saveFailed = function (error) {
};
Dataservice.prototype.saveFinished = function () {
this._isSaving = false;
};
return Dataservice;
})();
return Dataservice;
})
I do have a model tblMovie
using System;
using System.ComponentModel.DataAnnotations;
namespace DurandalMovieApp.Models
{
public class tblMovie
{
[Key]
public int MovieID { get; set; }
public string Title { get; set; }
public string Director { get; set; }
}
}
Hope someone can help!
I think that the problem is that your entity is: tblMovie, not tblMovies.
Try replacing:
return this.Manager.createEntity('tblMovies', initialValues);
With:
return this.Manager.createEntity('tblMovie', initialValues);