Laravel, Vue.js array empty - javascript

I'm totally new to the laravel and vue.js frameworks. For a school project with have to create an app that uses laravel for the back-end and vue.js for the front-end. So I created an API to use it afterwards in my vue.Js. But the problem is that when I want to get the data in my Vue.JS it tells me it has an empty array which should show all the values I have in my database (about 20). I have been struggling since 2 days on it and now, I'm totally lost, I don't know what to do or what goes wrong.. I tried my API into postman and it works perfect.
Specs:
-> Laravel 5.6
-> Vue 2.5.7
My API Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Note;
use App\Http\Resources\Note as NoteResource;
class NotesApiController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$notes = Note::all();
return NoteResource::collection($notes);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$note = new Note;
$note->user_id = $request -> input('user_id');
$note->course_id = $request -> input('course_id');
$note->title = $request -> input('title');
$note->body = $request -> input('body');
$note->file_name = $request -> input('file_name');
$note->save();
return new NoteResource($note);
return response() -> json('success', 200);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$note = Note::findOrFail($id);
return new NoteResource($note);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$note = Note::find($id);
$note->user_id = $request -> input('user_id');
$note->course_id = $request -> input('course_id');
$note->title = $request -> input('title');
$note->body = $request -> input('body');
$note->file_name = $request -> input('file_name');
$note->save();
return new NoteResource($note);
return response() -> json('success', 200);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$note = Note::find($id);
$note -> delete();
return response() -> json('success', 200);
}
}
My Note Resource:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Note extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'user_id' => $this->user_id,
'course_id' => $this->course_id,
'title' => $this->title,
'body' => $this->body,
'file_name' => $this->file_name,
'created_at' => $this->created_at->format('d/m/Y'),
'updated_at' => $this->updated_at->diffForHumans(),
];
}
}
API Routes:
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
// Route::middleware('auth:api')->get('/user', function (Request $request) {
// return $request->user();
// });
//Index Page Vue
Route::get('/', 'PagesControllerApi#index');
//Afficher la liste de toutes les notes
Route::get('notes', 'NotesApiController#index');
//Montre une note selon son id
Route::get('notes/{id}', 'NotesApiController#show');
//Enregistre la note
Route::post('notes', 'NotesApiController#store');
//Mise-à-jour d'une note
Route::put('notes/{id}', 'NotesApiController#update');
//Effacer une note
Route::delete('notes/{id}', 'NotesApiController#destroy');
APP.JS of Vue:
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
window.Vue = require('vue');
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.component('notes', require('./components/notes.vue'));
Vue.component('navbar', require('./components/navbar.vue'));
Vue.component('paginate', require('vuejs-paginate'));
const app = new Vue({
el: '#app'
});
My Note Component in Vue
<template>
<div>
<h2 class="m-4">Notes</h2>
</div>
</template>
<script>
export default {
data() {
return{
notes: [],
note: {
id: '',
user_id: '',
course_id: '',
title: '',
body: '',
file_name:'',
},
note_id: '',
pagination: {},
edit: false
};
},
created() {
this.fetchArticles();
},
methods: {
fetchArticles(page_url) {
let vm = this;
page_url = page_url || '/api/notes';
fetch(page_url)
.then(res => res.json())
.then(res => {
this.articles = res.data;
})
.catch(err => console.log(err));
},
}
}
</script>
index.blade.php
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<script>window.Laravel = { csrfToken: "{{ csrf_token() }}" }</script>
<title>{{ config("app.name", "Laravel") }}</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Raleway:300,400,600" rel="stylesheet" type="text/css">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
<navbar></navbar>
<div class="container">
<notes>
</notes>
</div>
</div>
</body>
</html>
API
Results
What the VUE Develope shows
Empty Array
Because of that I can't show any value on my page..
Thanks in advance!

It should be this.notes = res.data but you have this.articles = res.data;
Then you just need to loop over the array and access properties on the object, something like this:
<div v-for="(note, index) in notes" :key="`note-${key}`">
<h2 v-text="note.title"></h2>
<p v-text="note.body"></p>
<p v-text="note.filename"></p>
</div>

Related

Pusher: Callback function not executing with standalone Laravel (API) Vue.js(client) apps

Please I need help with pusher integration in my Laravel & Vue js project. NOT SPA (i.e separate Apps (Laravel - API & Vuejs- frontend)
The goal is to establish a real-time chat between two users.
The whole cycle is working perfectly well but the pusher callback is not executing, therefore making the chat function limited to the app API level only. It is not real-time which is why I'm integrating pusher to handle that.
Please see the code snippets below, ready to provide more on request. I've spent days on this, still can't figure out what I'm doing wrong.
Thanks in anticipation.
CommentController
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$user = Auth::user();
$validator = Validator::make($request->all(), [
'bid_id' => 'required',
'message' => ['required', 'string'],
]);
if ($validator->fails()) {
return response()->json(["error" => $validator->errors()], 400);
}
try {
$comment = $user->comments()->create([
'bid_id' => $request->bid_id,
'message' => $request->message,
]);
// Fire the comment broadcast event
// event(new CommentEvent($comment));
broadcast(new CommentEvent($user, $comment->load('user')))->toOthers();
} catch (Exception $exception) {
Log::error("Error while creating Comment" . $exception->getMessage());
} finally {
return response()->json(['comment' => $comment], 201);
}
}
CommentEvent.php
<?php
namespace App\Events;
use App\Models\Comment;
use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class CommentEvent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #param $comment
*
* #return void
*/
public $user;
public $comment;
public function __construct(User $user, Comment $comment)
{
$this->user = $user;
$this->comment = $comment;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PresenceChannel('comment-channel');
}
public function broadcastAs()
{
return 'CommentEvent';
}
}
Main.js
import Pusher from "pusher-js";
/* -------------------------------------------------------------------------- */
/* PUSHER CONFIG */
/* -------------------------------------------------------------------------- */
Pusher.logToConsole = true;
let pusher = new Pusher(process.env.VUE_APP_PUSHER_APP_KEY,{
cluster: process.env.VUE_APP_PUSHER_APP_CLUSTER,
encrypted: false,
});
Vue.prototype.$pusher = pusher;
App.vue
<script>
export default {
name: "App",
components: {},
created() {
let channel = this.$pusher.subscribe("comment-channel");
channel.bind("pusher:subscription_succeeded", function(members) {
console.log(members);
console.log("succesfully subscribed!");
});
channel.bind("CommentEvent", function(data) {
console.log(data);
this.$store.commit("ADD_COMMENT", data.comment);
});
},
methods: {
},
};
</script>
I've been able to resolve this using.
but I had to switch tech. The real-time chat system of my app is now driven by socket.io, Redis and a simple node js server wrapped within the API
I'll be willing to help with code snippets if you need me to.

How to render Google Pay button in Google Apps Script

I want to install a Google Pay button into my Google Apps Script and have it work similar to this demo.
Here is the documentation.
But when I use the following code, I don't see any payment button.
What am I doing wrong?
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script async
  src="https://pay.google.com/gp/p/js/pay.js"
  onload="onGooglePayLoaded()">
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
Code.gs
// https://developers.google.com/apps-script/guides/html#code.gs_1
// Use this code for Google Docs, Slides, Forms, or Sheets.
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.createMenu('Buy report')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
const html = HtmlService.createHtmlOutputFromFile( 'Index' );
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog( html, 'Dialog title' );
// .showSidebar( html, );
}
// ref: https://developers.google.com/pay/api/web/guides/resources/demos
// demo: https://jsfiddle.net/fw5t6caL/
/**
* Define the version of the Google Pay API referenced when creating your
* configuration
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#PaymentDataRequest|apiVersion in PaymentDataRequest}
*/
const baseRequest = {
apiVersion: 2,
apiVersionMinor: 0
};
/**
* Card networks supported by your site and your gateway
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#CardParameters|CardParameters}
* #todo confirm card networks supported by your site and gateway
*/
const allowedCardNetworks = ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"];
/**
* Card authentication methods supported by your site and your gateway
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#CardParameters|CardParameters}
* #todo confirm your processor supports Android device tokens for your
* supported card networks
*/
const allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];
/**
* Identify your gateway and your site's gateway merchant identifier
*
* The Google Pay API response will return an encrypted payment method capable
* of being charged by a supported gateway after payer authorization
*
* #todo check with your gateway on the parameters to pass
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#gateway|PaymentMethodTokenizationSpecification}
*/
const tokenizationSpecification = {
type: 'PAYMENT_GATEWAY',
parameters: {
'gateway': 'example',
'gatewayMerchantId': 'exampleGatewayMerchantId'
}
};
/**
* Describe your site's support for the CARD payment method and its required
* fields
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#CardParameters|CardParameters}
*/
const baseCardPaymentMethod = {
type: 'CARD',
parameters: {
allowedAuthMethods: allowedCardAuthMethods,
allowedCardNetworks: allowedCardNetworks
}
};
/**
* Describe your site's support for the CARD payment method including optional
* fields
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#CardParameters|CardParameters}
*/
const cardPaymentMethod = Object.assign(
{},
baseCardPaymentMethod,
{
tokenizationSpecification: tokenizationSpecification
}
);
/**
* An initialized google.payments.api.PaymentsClient object or null if not yet set
*
* #see {#link getGooglePaymentsClient}
*/
let paymentsClient = null;
/**
* Configure your site's support for payment methods supported by the Google Pay
* API.
*
* Each member of allowedPaymentMethods should contain only the required fields,
* allowing reuse of this base request when determining a viewer's ability
* to pay and later requesting a supported payment method
*
* #returns {object} Google Pay API version, payment methods supported by the site
*/
function getGoogleIsReadyToPayRequest() {
return Object.assign(
{},
baseRequest,
{
allowedPaymentMethods: [baseCardPaymentMethod]
}
);
}
/**
* Configure support for the Google Pay API
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#PaymentDataRequest|PaymentDataRequest}
* #returns {object} PaymentDataRequest fields
*/
function getGooglePaymentDataRequest() {
const paymentDataRequest = Object.assign({}, baseRequest);
paymentDataRequest.allowedPaymentMethods = [cardPaymentMethod];
paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
paymentDataRequest.merchantInfo = {
// #todo a merchant ID is available for a production environment after approval by Google
// See {#link https://developers.google.com/pay/api/web/guides/test-and-deploy/integration-checklist|Integration checklist}
// merchantId: '01234567890123456789',
merchantName: 'Example Merchant'
};
return paymentDataRequest;
}
/**
* Return an active PaymentsClient or initialize
*
* #see {#link https://developers.google.com/pay/api/web/reference/client#PaymentsClient|PaymentsClient constructor}
* #returns {google.payments.api.PaymentsClient} Google Pay API client
*/
function getGooglePaymentsClient() {
if ( paymentsClient === null ) {
paymentsClient = new google.payments.api.PaymentsClient({environment: 'TEST'});
}
return paymentsClient;
}
/**
* Initialize Google PaymentsClient after Google-hosted JavaScript has loaded
*
* Display a Google Pay payment button after confirmation of the viewer's
* ability to pay.
*/
function onGooglePayLoaded() {
const paymentsClient = getGooglePaymentsClient();
paymentsClient.isReadyToPay(getGoogleIsReadyToPayRequest())
.then(function(response) {
if (response.result) {
addGooglePayButton();
// #todo prefetch payment data to improve performance after confirming site functionality
// prefetchGooglePaymentData();
}
})
.catch(function(err) {
// show error in developer console for debugging
console.error(err);
});
}
/**
* Add a Google Pay purchase button alongside an existing checkout button
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#ButtonOptions|Button options}
* #see {#link https://developers.google.com/pay/api/web/guides/brand-guidelines|Google Pay brand guidelines}
*/
function addGooglePayButton() {
const paymentsClient = getGooglePaymentsClient();
const button =
paymentsClient.createButton({onClick: onGooglePaymentButtonClicked});
document.getElementById('container').appendChild(button);
}
/**
* Provide Google Pay API with a payment amount, currency, and amount status
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#TransactionInfo|TransactionInfo}
* #returns {object} transaction info, suitable for use as transactionInfo property of PaymentDataRequest
*/
function getGoogleTransactionInfo() {
return {
countryCode: 'US',
currencyCode: 'USD',
totalPriceStatus: 'FINAL',
// set to cart total
totalPrice: '1.00'
};
}
/**
* Prefetch payment data to improve performance
*
* #see {#link https://developers.google.com/pay/api/web/reference/client#prefetchPaymentData|prefetchPaymentData()}
*/
function prefetchGooglePaymentData() {
const paymentDataRequest = getGooglePaymentDataRequest();
// transactionInfo must be set but does not affect cache
paymentDataRequest.transactionInfo = {
totalPriceStatus: 'NOT_CURRENTLY_KNOWN',
currencyCode: 'USD'
};
const paymentsClient = getGooglePaymentsClient();
paymentsClient.prefetchPaymentData(paymentDataRequest);
}
/**
* Show Google Pay payment sheet when Google Pay payment button is clicked
*/
function onGooglePaymentButtonClicked() {
const paymentDataRequest = getGooglePaymentDataRequest();
paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
const paymentsClient = getGooglePaymentsClient();
paymentsClient.loadPaymentData(paymentDataRequest)
.then(function(paymentData) {
// handle the response
processPayment(paymentData);
})
.catch(function(err) {
// show error in developer console for debugging
console.error(err);
});
}
/**
* Process payment data returned by the Google Pay API
*
* #param {object} paymentData response from Google Pay API after user approves payment
* #see {#link https://developers.google.com/pay/api/web/reference/response-objects#PaymentData|PaymentData object reference}
*/
function processPayment(paymentData) {
// show returned data in developer console for debugging
console.log(paymentData);
// #todo pass payment token to your gateway to process payment
paymentToken = paymentData.paymentMethodData.tokenizationData.token;
}
I think that when your script is the actual tested script, the Javascript is required to be included in the HTML side. So how about the following modification?
Modified script:
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script async
src="https://pay.google.com/gp/p/js/pay.js"
onload="onGooglePayLoaded()">
</script>
</head>
<body>
<div id="container"></div>
</body>
<script>
// ref: https://developers.google.com/pay/api/web/guides/resources/demos
// demo: https://jsfiddle.net/fw5t6caL/
/**
* Define the version of the Google Pay API referenced when creating your
* configuration
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#PaymentDataRequest|apiVersion in PaymentDataRequest}
*/
const baseRequest = {
apiVersion: 2,
apiVersionMinor: 0
};
/**
* Card networks supported by your site and your gateway
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#CardParameters|CardParameters}
* #todo confirm card networks supported by your site and gateway
*/
const allowedCardNetworks = ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"];
/**
* Card authentication methods supported by your site and your gateway
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#CardParameters|CardParameters}
* #todo confirm your processor supports Android device tokens for your
* supported card networks
*/
const allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];
/**
* Identify your gateway and your site's gateway merchant identifier
*
* The Google Pay API response will return an encrypted payment method capable
* of being charged by a supported gateway after payer authorization
*
* #todo check with your gateway on the parameters to pass
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#gateway|PaymentMethodTokenizationSpecification}
*/
const tokenizationSpecification = {
type: 'PAYMENT_GATEWAY',
parameters: {
'gateway': 'example',
'gatewayMerchantId': 'exampleGatewayMerchantId'
}
};
/**
* Describe your site's support for the CARD payment method and its required
* fields
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#CardParameters|CardParameters}
*/
const baseCardPaymentMethod = {
type: 'CARD',
parameters: {
allowedAuthMethods: allowedCardAuthMethods,
allowedCardNetworks: allowedCardNetworks
}
};
/**
* Describe your site's support for the CARD payment method including optional
* fields
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#CardParameters|CardParameters}
*/
const cardPaymentMethod = Object.assign(
{},
baseCardPaymentMethod,
{
tokenizationSpecification: tokenizationSpecification
}
);
/**
* An initialized google.payments.api.PaymentsClient object or null if not yet set
*
* #see {#link getGooglePaymentsClient}
*/
let paymentsClient = null;
/**
* Configure your site's support for payment methods supported by the Google Pay
* API.
*
* Each member of allowedPaymentMethods should contain only the required fields,
* allowing reuse of this base request when determining a viewer's ability
* to pay and later requesting a supported payment method
*
* #returns {object} Google Pay API version, payment methods supported by the site
*/
function getGoogleIsReadyToPayRequest() {
return Object.assign(
{},
baseRequest,
{
allowedPaymentMethods: [baseCardPaymentMethod]
}
);
}
/**
* Configure support for the Google Pay API
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#PaymentDataRequest|PaymentDataRequest}
* #returns {object} PaymentDataRequest fields
*/
function getGooglePaymentDataRequest() {
const paymentDataRequest = Object.assign({}, baseRequest);
paymentDataRequest.allowedPaymentMethods = [cardPaymentMethod];
paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
paymentDataRequest.merchantInfo = {
// #todo a merchant ID is available for a production environment after approval by Google
// See {#link https://developers.google.com/pay/api/web/guides/test-and-deploy/integration-checklist|Integration checklist}
// merchantId: '01234567890123456789',
merchantName: 'Example Merchant'
};
return paymentDataRequest;
}
/**
* Return an active PaymentsClient or initialize
*
* #see {#link https://developers.google.com/pay/api/web/reference/client#PaymentsClient|PaymentsClient constructor}
* #returns {google.payments.api.PaymentsClient} Google Pay API client
*/
function getGooglePaymentsClient() {
if ( paymentsClient === null ) {
paymentsClient = new google.payments.api.PaymentsClient({environment: 'TEST'});
}
return paymentsClient;
}
/**
* Initialize Google PaymentsClient after Google-hosted JavaScript has loaded
*
* Display a Google Pay payment button after confirmation of the viewer's
* ability to pay.
*/
function onGooglePayLoaded() {
const paymentsClient = getGooglePaymentsClient();
paymentsClient.isReadyToPay(getGoogleIsReadyToPayRequest())
.then(function(response) {
if (response.result) {
addGooglePayButton();
// #todo prefetch payment data to improve performance after confirming site functionality
// prefetchGooglePaymentData();
}
})
.catch(function(err) {
// show error in developer console for debugging
console.error(err);
});
}
/**
* Add a Google Pay purchase button alongside an existing checkout button
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#ButtonOptions|Button options}
* #see {#link https://developers.google.com/pay/api/web/guides/brand-guidelines|Google Pay brand guidelines}
*/
function addGooglePayButton() {
const paymentsClient = getGooglePaymentsClient();
const button =
paymentsClient.createButton({onClick: onGooglePaymentButtonClicked});
document.getElementById('container').appendChild(button);
}
/**
* Provide Google Pay API with a payment amount, currency, and amount status
*
* #see {#link https://developers.google.com/pay/api/web/reference/request-objects#TransactionInfo|TransactionInfo}
* #returns {object} transaction info, suitable for use as transactionInfo property of PaymentDataRequest
*/
function getGoogleTransactionInfo() {
return {
countryCode: 'US',
currencyCode: 'USD',
totalPriceStatus: 'FINAL',
// set to cart total
totalPrice: '1.00'
};
}
/**
* Prefetch payment data to improve performance
*
* #see {#link https://developers.google.com/pay/api/web/reference/client#prefetchPaymentData|prefetchPaymentData()}
*/
function prefetchGooglePaymentData() {
const paymentDataRequest = getGooglePaymentDataRequest();
// transactionInfo must be set but does not affect cache
paymentDataRequest.transactionInfo = {
totalPriceStatus: 'NOT_CURRENTLY_KNOWN',
currencyCode: 'USD'
};
const paymentsClient = getGooglePaymentsClient();
paymentsClient.prefetchPaymentData(paymentDataRequest);
}
/**
* Show Google Pay payment sheet when Google Pay payment button is clicked
*/
function onGooglePaymentButtonClicked() {
const paymentDataRequest = getGooglePaymentDataRequest();
paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
const paymentsClient = getGooglePaymentsClient();
paymentsClient.loadPaymentData(paymentDataRequest)
.then(function(paymentData) {
// handle the response
processPayment(paymentData);
})
.catch(function(err) {
// show error in developer console for debugging
console.error(err);
});
}
/**
* Process payment data returned by the Google Pay API
*
* #param {object} paymentData response from Google Pay API after user approves payment
* #see {#link https://developers.google.com/pay/api/web/reference/response-objects#PaymentData|PaymentData object reference}
*/
function processPayment(paymentData) {
// show returned data in developer console for debugging
console.log(paymentData);
// #todo pass payment token to your gateway to process payment
paymentToken = paymentData.paymentMethodData.tokenizationData.token;
}
</script>
</html>
Code.gs
// https://developers.google.com/apps-script/guides/html#code.gs_1
// Use this code for Google Docs, Slides, Forms, or Sheets.
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.createMenu('Buy report')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
const html = HtmlService.createHtmlOutputFromFile( 'Index' );
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog( html, 'Dialog title' );
// .showSidebar( html, );
}

Pusher notification with Laravel 5.4 not working as expected

So I'm really stuck for a while now, with Laravel event and pusher API.
I created event and broadcast, but when I access with pusher Javascript API it returns empty array, when I try to print it in the route it also returns empty array, meanwhile if I check Laravel log stoarage/logs/laravel.log I see exactly what I am expecting in the Javascript and route.
My code:
.env
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=******
PUSHER_APP_KEY=524**************8
PUSHER_APP_SECRET=d2**************c
Boadcasting.php
'default' => env('BROADCAST_DRIVER', 'pusher'),
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'us2',
'encrypted' => true
],
],
The event class: ProjectEvent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class ProjectEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $username;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($username)
{
$this->username = $username;
$this->message = "{$username} sent you a message";
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn()
{
return ['project-update'];
}
}
Route:
Route::get('/test', function () {
print_r(event(new App\Events\ProjectEvent('Michel')));
//return "Event has been sent!";
});
Route::get('/view', function () {
return view('testevent');
});
testevent.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://js.pusher.com/3.1/pusher.min.js"></script>
<script type="text/javascript">
Pusher.logToConsole = true;
var pusher = new Pusher('524************8', {
cluster: 'us2',
encrypted: true
});
var channel = pusher.subscribe('project-update');
channel.bind('App\\Events\\ProjectEvent', function(data) {
alert(data.message);
});
</script>
</body>
</html>
I really can't figure out where it all going wrong, since I am able to see the event in the log while the JS alert isn't working, also I try to dump the event on the route, it return empty array()

Laravel 5.3 not sending Events to pusher

I'm using laravel 5.3 for my website. I needed to add real time functionality to my app so I used pusher. but the problem is when the event has been triggered nothing happened and no events sent to pusher.
my pusher configuration in broadcasting.php file :
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_KEY'),
'secret' => env('PUSHER_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'eu',
'encrypted'=>true
],
],
my event class:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class ChatEvent implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $data;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn()
{
// return new PrivateChannel('test-channel');
return ['test-channel'];
}
and my pusher javascript code:
Pusher.logToConsole = true;
var pusher = new Pusher('pusher_id', {
cluster:'eu',
encrypted: true
});
var channel = pusher.subscribe('test-channel');
channel.bind('App\\Events\\ChatEvent', function(data) {
console.log(data);
alert(data);
});
Check your Pusher credentials in your .env file.
PUSHER_KEY should be PUSHER_APP_KEY
PUSHER_SECRET should be PUSHER_APP_SECRET

Angular, Laravel 4 and MySQL database best practices

I am pretty new to Angular and have a bit of experience with Laravel 4.
I am building an app where the user can edit "on-the-fly" but also save to a MySQL.
The initial plan was to use Angular to manage the live editing, and to store and retrieve data to the MySQL DB using Eloquent. I am aware you can connect to DB via Angular, but I'd like to know what the best solution would be.
Is it best to keep it separated or to use Angular for everything?
Is there some performance issues if using Angular for everything?
Is Angular as easy to use as Eloquent for DB interactions ?
If I use Eloquent for DB, is it straight-forward to pass data to Angular?
I have already started building the live-editing part of the app with Angular and I have to say I found it very easy to learn and extremely powerful. I now have to make a decision as to how I will handle storage.
Thank you
Check out this tutorial by the great Dave Mosher, I think it might be exactly what you're looking for, he uses Laravel, Angular, and MySQL:
Youtube Screencast: http://www.youtube.com/watch?v=hqAyiqUs93c
Source code: https://github.com/davemo/end-to-end-with-angularjs
The best way to use angular.js and laravel is, using a REST API.
For example, if you have an admin panel to manage users, the method will be,
In your route,
Route::resource('users', 'UsersController');
The controller looks like this,
<?php
/**
*
* Users Controller
*
*/
class UsersController extends AdminController {
/**
* Display all users.
*
* #return Response
*/
public function index() {
$users = User::where('id', '!=', Auth::user()->id)->get();
return Response::json(array(
'status' => 'success',
'users' => $users->toArray()),
200
);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create() {
//
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store() {
// add some validation also
$input = Input::all();
$user = new User;
if ( $input['name'] ) {
$user->name = $input['name'];
}
if ( $input['username'] ) {
$user->username = $input['username'];
$user->password = Hash::make($input['username']);
}
if ( $input['email'] ) {
$user->email = $input['email'];
}
$user->save();
return Response::json(array(
'status' => 'success',
'users' => $user->toArray()),
200
);
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id) {
$user = User::where('id', $id)
->take(1)
->get();
return Response::json(array(
'error' => false,
'users' => $user->toArray()),
200
);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id) {
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id) {
// add some validation also
$input = Input::all();
$user = User::find($id);
if ( $input['name'] ) {
$user->name = $input['name'];
}
if ( $input['username'] ) {
$user->username = $input['username'];
}
if ( $input['email'] ) {
$user->email = $input['email'];
}
$user->save();
return Response::json(array(
'status' => 'success',
'message' => 'User Updated'),
200
);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id) {
$user = User::find($id);
$user->delete();
return Response::json(array(
'status' => 'success',
'message' => 'User Deleted'),
200
);
}
}
Then the script,
var app = angular.module('myApp', []);
// include this in php page to define root path
app.factory('Data', function(){
return {
root_path: "<?php echo Request::root(); ?>/"
};
});
GET - Get all users
$http({method: 'GET', url: Data.root_path + 'users'}).
success(function(data, status, headers, config) {
$scope.users = data.users;
}).
error(function(data, status, headers, config) {
$scope.users = [];
});
GET - Get single user for edit
$http({method: 'GET', url: Data.root_path + 'users/'+id}).
success(function(data, status, headers, config) {
$scope.entry = data.users[0];
}).
error(function(data, status, headers, config) {
$scope.entry = [];
});
PUT - Update single user
$http.put(Data.root_path + 'users/'+entry.id, entry).
success(function(data, status, headers, config) {
//
}).
error(function(data, status, headers, config) {
//
});
POST - Save new user
$http.post(Data.root_path + 'users', entry).
success(function(data, status, headers, config) {
//
}).
error(function(data, status, headers, config) {
//
});
DELETE - Delete a user
$http.delete(Data.root_path +'users/'+id)
.success(function(response) {
//
})
.error(function(response) {
//
});
Create RESTful endpoints to manage resources using Laravel. This is dead simple with the resource controller as already pointed out:
Route::resource('user', 'UsersController');
Then you use an AngularJS resource to interact with that. Example (from docs) of fetching a user, editing the model and then saving (calling via the $ in the callback).
var User = $resource('/user/:userId', {userId:'#id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
http://docs.angularjs.org/api/ngResource.$resource
Even better, create an Angular JS Service for the resource so you can just inject that into multiple controllers and get all the methods defined.
Here's a great post on how to set this up:
http://blog.brunoscopelliti.com/building-a-restful-web-service-with-angularjs-and-php-more-power-with-resource

Categories

Resources