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',
];
}
}
Related
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
i have a class and a function named getStationDetail and i want to send a request to server and get the value and save it to dataFromServer variable
and i want to return that but when i cal that i get empty array
export class StationService {
dataFromServer: any = [];
constructor(private rest: RestService) { }
getStationsDetail() {
this.rest.sendRequest('GET', 'station', null).subscribe(
value => {
this.dataFromServer = value['Station'];
// return this.dataFromServer;
},
);
return this.dataFromServer;
}
}
and i cal it
export class StationComponent implements OnInit(){
mm: any;
ngOnInit() {
this.mm = this._stationService.getStationsDetail().subscribe();
console.log(this.mm);
}
}
but map not worked? how to cal subscribe?
When a request is sent to server then cursor doesn't stop to execute next lines of codes if we want some operations after receiving the response from server then we use observables and do these methods in subscribe(). so for examples:
ngOnInit() {
this._stationService.getStationsDetail()
.subscribe(stationDetails => {
console.log('Response array:' , stationDetails);
});}
The data I am trying to access from the API is formatted like below:
{
“array1”:[
{"id”:1, ”someProperty”:”A"},
{"id":2, "someProperty”:”B”}
],
“array2”:[
{"id”:1, ”anotherProperty”:”foo”, ”lastProperty”:”foo2”},
{"id":2, "anotherProperty”:”bar”, ”lastProperty”:”bar2”}
]
}
The Dependencies class:
import { FirstArray } from './first-array';
import { SecondArray } from './second-array';
export class Dependencies {
constructor(
public array1: Array<FirstArray>,
public array2: Array<SecondArray>
) { }
}
The FirstArray class:
export class FirstArray {
constructor(
public id: number,
public someProperty: string
) { }
}
The SecondArray class:
export class SecondArray {
constructor(
public id: number,
public anotherProperty: string,
public lastProperty: string
) { }
}
My Dependencies service.ts file:
/** GET all Dependencies from the server */
getAllDependencies (): Observable<Dependencies[]> {
return this.http.get<Dependencies[]>(apiUrl).pipe(
tap(allDependencies => this.log('fetched allDependencies')),
catchError(this.handleError('getAllDependencies', []))
);
}
The component.ts file:
ngOnInit() {
this.getAllDependencies();
console.log("allDependencies:",this.allDependencies);
}
allDependencies: Dependencies[];
getAllDependencies(): void {
this.DependenciesService.getAllDependencies()
.subscribe(allDependencies => this.allDependencies = allDependencies);
}
When I try console.log(this.allDependencies) in the component file, the result is undefined. The data is retrieved from the API correctly- 'fetched allDependencies' is printed in the logs, and I can print the Dependencies object in the logs just fine by stringifying from the service file:
/** GET all Dependencies from the server */
getAllDependencies (): Observable<Dependencies[]> {
return this.http.get<Dependencies[]>(apiUrl).pipe(
tap(allDependencies => this.log(JSON.stringify(allDependencies))),
catchError(this.handleError('getAllDependencies', []))
);
}
My question: how can I access this data from my component file? I think I'm missing something in my data structures somewhere, or I have a Typescript-related error, but I am not sure.
The biggest issue you have is that within your component, the method that calls your service is void and doesn't return anything...
It doesn't really add any value, so remove it and access the data like this:
ngOnInit() {
this.DependenciesService.getAllDependencies()
.subscribe(allDependencies => {
this.allDependencies = allDependencies;
console.log(this.allDependencies); // multi-line with log.
});
}
Updated as per your comment:
Change your method from getAllDependencies(): void to getAllDependencies(): Observable<Dependencies[]> and call within ngOnOnit
getAllDependencies(): Observable<Dependencies[]> {
return this.DependenciesService.getAllDependencies();
}
ngOnInit() {
this.getAllDependencies().subscribe(.....);
}
I'm using laravel, and im trying to check to see if a user is following a user, if so the text box will change from follow to following.
I can get the id of the user easily but i can't check to see if a user has followable id
I need to reference the pivot object, and this object only shows when i do
<div id="profile" data='{{ $myuser->followers}}'></div>
but i need to use $myuser variable by itself.
This is what i have so far.
Profile.blade.php
<div id="profile" data='{{ $myuser}}'></div>
Profile.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
export default class Example extends Component {
constructor(props){
super(props);
let id = JSON.parse(this.props.data);
// console.log('data from component', JSON.parse(this.props.data));
this.state = {
btnText: 'Follow',
className: 'follow-button',
user:{
// i can get a user id, but i cant get the followable id.
id:id.id,
followers:id.pivot.followable_id
}
};
}
myfollow(user) {
axios('/user/follow/'+ this.state.user.id , { method: "POST" })
.then(response => {
console.log(response);
});
};
componentDidMount(){
console.log('data from component', this.state.user.followers);
// if (this.state.user.followers === 3){
// this.setState({
// btnText:'Following',
// className:'following-button'
// });
// }
}
UserController.php
public function getProfile($user)
{
$users = User::with(['posts.likes' => function($query) {
$query->whereNull('deleted_at');
$query->where('user_id', auth()->user()->id);
}, 'follow','follow.follower'])
->where('name','=', $user)->get();
$user = $users->map(function(User $myuser){
$myuser['followedByMe'] = $myuser->follow->count() == 0 ? false : true;
return $myuser;
});
if(!$user){
return redirect('404');
}
return view ('profile')->with('user', $user);
}
MyFollow.php (model)
public function followedByMe()
{
foreach($this->follower as $followers) {
if ($followers->user_id == auth()->id()){
return true;
}
}
return false;
}
User.php Model
?php
namespace App;
use App\User;
use App\Post;
use App\GalleryImage;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\MyFollow;
use Overtrue\LaravelFollow\Traits\CanFollow;
use Overtrue\LaravelFollow\Traits\CanBeFollowed;
class User extends Authenticatable
{
use Notifiable,CanFollow, CanBeFollowed;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts()
{
return $this->hasMany(Post::class);
}
public function images()
{
return $this->hasMany(GalleryImage::class, 'user_id');
}
public function likes()
{
return $this->hasMany('App\Like');
}
public function follow()
{
return $this->hasMany('App\MyFollow');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
}
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.