Laravel Echo not receiving Pusher notifications in realtime - ideas? - laravel

I am trying to implement a user messaging approach using ideas from this site:
https://www.sitepoint.com/add-real-time-notifications-laravel-pusher/
The key idea is using the laravel notifications capability to update a notifications table (for purposes of marking off messages as read) and at same time broadcast to pusher as a private channel and listen in client via Laravel Echo.
I want to send notifications when I add a new exercise, so I use the EventServiceProvider to listen to a database create event and that is where I trigger the notification:
Exercise::created(function ($exercise) {
foreach ($users as $user) {
$user->notify(new NewExercisePosted($user, $exercise));
}
The notification:
class NewExercisePosted extends Notification implements ShouldBroadcast
{
//use Queueable;
protected $exercise;
protected $user;
public function __construct(User $user, Exercise $exercise)
{
$this->user = $user;
$this->exercise = $exercise;
}
public function via($notifiable)
{
return ['database', 'broadcast'];
}
public function toArray($notifiable)
{
return [
'id' => $this->id,
'read_at' => null,
'data' => [
'user_id' => $this->user->id,
'ex_id' => $this->exercise->id,
],
];
}
}
This is just populating the notifications table and broadcasting to pusher.
Here is my master view file:
<!DOCTYPE html>
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="/css/app.css")/>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
<!-- This makes the current user's id available in javascript -->
#if(!auth()->guest())
<script>
window.Laravel.userId = <?php echo auth()->user()->id; ?>
</script>
#endif
</head>
<body>
#include('partials/header')
#if(Session::has('message'))
<div class="alert alert-info">
{{Session::get('message')}}
</div>
#endif
#yield('content')
#include('partials/footer')
#include('partials/analytics')
<script src="/js/app.js"></script>
</body>
</html>
Here is the relevant part of the header view where I have the messages appear:
<li class="dropdown">
<a class="dropdown-toggle" id="notifications" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
<span class="glyphicon glyphicon-user"></span>
</a>
<ul class="dropdown-menu" aria-labelledby="notificationsMenu" id="notificationsMenu">
<li class="dropdown-header">No notifications</li>
</ul>
</li>
Here is my app.js:
require('./bootstrap');
var app = 0;
window._ = require('lodash');
window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');
$(document).ready(function () {
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
});
window.Pusher = require('pusher-js');
import Echo from "laravel-echo";
const PUSHER_KEY = 'blah';
const NOTIFICATION_TYPES = {
follow: 'App\\Notifications\\UserFollowed',
newEx: 'App\\Notifications\\NewExercisePosted'
};
window.Echo = new Echo({
broadcaster: 'pusher',
key: PUSHER_KEY,
cluster: 'mt1',
encrypted: true
});
var notifications = [];
$(document).ready(function() {
// check if there's a logged in user
if(Laravel.userId) {
// load notifications from database
$.get(`/notifications`, function (data) {
addNotifications(data, "#notifications");
});
// listen to notifications from pusher
window.Echo.private(`App.User.${Laravel.userId}`)
.notification((notification) => {
addNotifications([notification], '#notifications');
});
}
});
function addNotifications(newNotifications, target) {
console.log(notifications.length);
notifications = _.concat(notifications, newNotifications);
// show only last 5 notifications
notifications.slice(0, 5);
showNotifications(notifications, target);
}
function showNotifications(notifications, target) {
if(notifications.length) {
var htmlElements = notifications.map(function (notification) {
return makeNotification(notification);
});
$(target + 'Menu').html(htmlElements.join(''));
$(target).addClass('has-notifications')
} else {
$(target + 'Menu').html('<li class="dropdown-header">No notifications</li>');
$(target).removeClass('has-notifications');
}
}
// Make a single notification string
function makeNotification(notification) {
var to = routeNotification(notification);
//console.log(to);
var notificationText = makeNotificationText(notification);
return '<li>' + notificationText + '</li>';
}
function routeNotification(notification) {
//console.log(notification.data.data.ex_id);
var to = `?read=${notification.id}`;
if(notification.type === NOTIFICATION_TYPES.follow) {
to = 'users' + to;
} else if(notification.type === NOTIFICATION_TYPES.newEx) {
const exId = notification.data.data.ex_id;
to = `guitar-lesson-ex/${exId}` + to;
}
return '/' + to;
}
function makeNotificationText(notification) {
var text = '';
if(notification.type === NOTIFICATION_TYPES.follow) {
const name = notification.data.follower_name;
text += `<strong>${name}</strong> followed you`;
} else if(notification.type === NOTIFICATION_TYPES.newEx) {
text += `New exercise posted`;
}
return text;
}
Things are working somewhat, but not quite. Messages are appearing in database and in Pusher right away after I create a new exercise, and when you click the MarkAsRead notification the notification is being marked off as read. Here is the problem:
When I create a new exercise, the client doesn't update in realtime. It only seems to produce a change when the page is refreshed.
Based on what I have above, any tips on how to fix things? I am clueless about javascript, especially about scope of variables, order of execution, etc, etc. So I suspect I have overlooked some finer points. I am a guitarist before I am a developer!
Thanks!
Brian

I spent all day yesterday trying to figure this out and in the end it came down to * vs {id}...
The problem was in the channels.php file where channel authorization is done. I was using App.User.{id} not realizing that was per 5.4 instructions when in fact for 5.3 needs to be App.User.*
I simply didn't even think to consider that! Now everything is working as expected.
thanks, Brian

Related

Chartisan/Laravel - > "Call to undefined method" error

I am trying to figure out how to use Chartisan and my controllers in Laravel. Having spend a couple of days on this, I have to admit that I am missing some fundamental because I understand the error, I just can't fix it..
What I have done so far is followed this https://charts.erik.cat/guide/installation.html#publish-the-configuration-file and reading multiple other guides online on how to solve it. If I stick to the guide, with the basic example then it works fine, but I want to create multiple charts, based on id/user variables which require I get the information from my database..
My problem is: "Call to undefined method App\Charts\SampleChart::labels()"
Are there anyone who has experience with this issue and tell me how to fix?
SampleChart.php (location: app/Charts/SampleChart.php)
declare(strict_types = 1);
namespace App\Charts;
use Chartisan\PHP\Chartisan;
use ConsoleTVs\Charts\BaseChart;
use Illuminate\Http\Request;
class SampleChart extends BaseChart
{
/**
* Handles the HTTP request for the given chart.
* It must always return an instance of Chartisan
* and never a string or an array.
*/
public ?string $name = 'my_chart';
public ?string $routeName = 'my_chart';
public function handler(Request $request): Chartisan
{
return Chartisan::build();
}
}
My Controller is:
namespace App\Http\Controllers;
use App\Charts\SampleChart;
use App\Charts\ExerciseInsight;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ExerciseInsightChartController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request): Chartisan
{
$samplechart = new Samplechart;
$exercise = 16;
$created_at = [];
$exercise_name = [];
$exercise_weight = [];
$exercise_rep = [];
$records = DB::table('dump_all_records')->where('exercise_id',"=", $exercise)->get();
foreach ($records as $record)
{
array_push($created_at, $record->created_at);
array_push($exercise_name, $record->exercise_name);
array_push($exercise_weight, $record->exercise_unit_value);
array_push($exercise_rep, $record->exercise_round_value);
}
// dd($samplechart);
$samplechart->labels($created_at);
$samplechart->dataset(['Weight','line', $exercise_weight]);
// $samplechart->dataset('Reps','line', $exercise_rep);
return view('insight.exercise_insight', compact('samplechart'));
}
}
my view is:
<!-- Charting library -->
<script src="https://unpkg.com/echarts/dist/echarts.min.js"></script>
<!-- Chartisan -->
<script src="https://unpkg.com/#chartisan/echarts/dist/chartisan_echarts.js"></script>
<!-- Chart's container -->
<div id="chart" style="height: 300px;"></div>
<script>
const chart = new Chartisan({
el: '#chart',
url: "#chart('my_chart')",
hooks: new ChartisanHooks()
.colors(['#4299E1','#FE0045','#C07EF1','#67C560','#ECC94B'])
// .datasets([{ type: 'line', fill: false }, 'bar'])
.datasets(
[
{
type: 'line',
fill: true ,fillColor : 'rgba(38,198,218,1)',
strokeColor : 'rgba(38,198,218,0)',
pointColor : '#26c6da',
pointStrokeColor : 'rgba(38,198,218,0)',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(38,198,218,1)',
},
{
type: 'line',
fill: true
}
]
)
.axis(true)
.tooltip()
});
</script>
Since the documentation has wroten, you can pass the data manually using data : {...} property.
So, the first step is call the Chartisan class, but don't forget to call the ServerData Class first, because the Chartisan Class constructor need parameter a ServerData Class.
In YourController.php
use Chartisan\PHP\Chartisan;
use Chartisan\PHP\ServerData;
In your method,
public function index () {
$serverdata = new ServerData;
$chart = new Chartisan($serverdata);
$chart->labels(
['First', 'Second', 'Third', 'Four', 'Five',
'Six', 'Seven', 'Eight', 'Nine', 'Ten']);
/**
* This your query will be placed,
* just for example :
*/
for ($i = 1; $i < mt_rand(5,9); $i++) {
$chart->dataset('Attribute '. $i, [
mt_rand(3,50), mt_rand(3,50), mt_rand(3,50), mt_rand(3,50), mt_rand(3,50),
mt_rand(3,50), mt_rand(3,50), mt_rand(3,50), mt_rand(3,50), mt_rand(3,50)
]);
}
/**Please remember on this chartisan version,
* Chartisan class will return an Object
* But the frontend loader just read a JSON format only.
* so it's easily to call Chartisan toJSON method.
* */
$chart = $chart->toJSON();
return view('your.view', [
'chart' => $chart,
]);
}
Next, in your blade view, this must be same scheme to load the chart according the documentation. But don't forget to escape $chart variable at blade syntax.
<script>
const chart = new Chartisan({
el: '#chart',
data: {!! $chart !!},
hooks: new ChartisanHooks()
.title({
textAlign: 'center',
left: '50%',
text: 'Example Chart Title',
})
.colors()
.datasets('line')
.axis(true)
.tooltip()
});
</script>
And the html part,
<!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.0">
<title>Document</title>
</head>
<body>
<div class="container">
<!-- here your chart-->
<div id="chart" style="height: 300px;"></div>
</div>
</body>
</html>
CMIIW. Hope its help.
Thank you.

Laravel cashier stripe issue with 3d secure cards not redirection to confirmation page

Im struggling to get a Laravel Cashier Strip integration to work with 3d secure cards.
I have go it setup so subscription works and is showing up in my stripe dashboard and everything it getting to my local database.
But when I test with cards that needs strong authntication as 3ds they get the status of incomplete in my stripe dashboard.
I get the cashier.payment response page in my console log. but isn't Cashier supposed to redirect to this confirmation window?
My code is as follows
In my subscription controller i have
public function index() {
$data = [
'intent' => auth()->user()->createSetupIntent(),
// 'plans' => $available_plans
];
return view('artists.subscription')->with($data);
}
public function checkout(Request $request) {
$user = auth()->user();
$paymentMethod = $request->payment_method;
$planId = 'monthly_sub';
// SCA
try {
$subscription = $user->newSubscription('monthly', $planId)->create($paymentMethod);
} catch (IncompletePayment $exception) {
return redirect()->route(
'cashier.payment',
[$exception->payment->id, 'redirect' => route('front')]
);
}
// return response(['status' => 'Success']);
}
and in my stripe js file I have this
const stripe = Stripe('stripe_key'); // i have my test key here
const elements = stripe.elements();
const cardElement = elements.create('card',{hidePostalCode: true});
cardElement.mount('#card-element');
const cardHolderName = document.getElementById('card-holder-name');
const cardButton = document.getElementById('card-button');
const clientSecret = cardButton.dataset.secret;
cardButton.addEventListener('click', async (e) => {
const { setupIntent, error } = await stripe.confirmCardSetup(
clientSecret, {
payment_method: {
card: cardElement,
billing_details: { name: cardHolderName.value }
}
}
);
axios.post('checkout', {
payment_method: setupIntent.payment_method
}).then(response => {
console.log(response.request.responseURL)
})
.catch(error => {
console.log(error.response)
});
});
My blade view is
#extends('layouts.app')
#section('head')
#php
// dd($intent);
#endphp
<script src="https://js.stripe.com/v3/"></script>
<link href="{{ asset('css/stripe.css') }}" rel="stylesheet">
#endsection
#section('content')
<input id="card-holder-name" type="text">
<!-- Stripe Elements Placeholder -->
<div id="card-element"></div>
<button id="card-button" data-secret="{{ $intent->client_secret }}">
subscribe
</button>
#endsection
#section('js')
<script src="{{ asset('js/stripe.js') }}" type="text/javascript"></script>
#endsection
Everything seems to be working but I just get the 3ds confirmation page as a response in my console. How do I get laravel to redirect and open that page for the user?
I think the issue is the order of events, your code should wait for 3DS to be called and completed before calling back to your code after the result is handed back to you. Using this regulator card [1] you should be able to test that with some small changes like this (I had to remove some things but this should be a reference):
stripe.confirmCardSetup(
"seti_xxx", {
payment_method: {
card: card,
billing_details: { name: "Name" }
}
}).then(function(result) {
// Check the result status here!!
axios.post('checkout', {
payment_method: result.setupIntent.payment_method
}).then(response => {
console.log(response.request.responseURL)
}).catch(error => {
console.log(error.response)
});
});
Hope this helps!
[1] https://stripe.com/docs/testing#regulatory-cards

Jaxon doesn´t return anything on response

Please, can anyone help?
I´m starting to use jaxon 3, planning to migrate from xajax. On a php7.3 plataform, I made a simple code, just to load jaxon and run a single alert script, but its returning nothing on browser. There are no errors on server log and no info on browser, no even on the chrome debug console.
Here is the simple code:
<?php
require_once( 'Jaxon/vendor/autoload.php' );
use Jaxon\Jaxon;
use Jaxon\Response\Response;
$ajax = jaxon();
$ajax->setOption('core.debug.on', false);
$ajax->setOption('core.prefix.function', 'jaxon_');
$ajax->setOption('core.request.uri', 'ajax.php');
$objResponse = new Response();
$objResponse->alert('test');
return $objResponse;
echo 'tests';
?>
PS: I didn´t use the jaxon word on tag cause the editor doesn´t let me do it
I would tell you to delete the echo at the end, and try to code some functions even for testing, so you can better understand v3.
Here, check this code, it might help you, this code is tested and will work.
<?php
require_once ($_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php');
use Jaxon\Jaxon;
use Jaxon\Response\Response;
$jaxon = jaxon();
$jaxon->setOption('js.app.minify', TRUE);
$jaxon->setOption('js.lib.uri', '/vendor/jaxon-php/jaxon-js/dist');
/** ################################# */
/** using jaxon with just functions then you have to register each function
*
* call these functions like this:
* jaxon_demo1();
* jaxon_demo2();
*
* <button type="button" onclick="jaxon_demo1()"> call fn 1 </button>
* <button type="button" onclick="jaxon_demo2()"> call fn 2 </button>
*
*/
$jaxon->register(Jaxon::USER_FUNCTION, 'demo1');
$jaxon->register(Jaxon::USER_FUNCTION, 'demo2');
$jaxon->register(Jaxon::CALLABLE_FUNCTION, 'functionThatReturnsUsing_setReturnValue', ['mode' => "'synchronous'"]);
function demo1(){
$jaxonResponse = new Response();
$jaxonResponse->alert('Hello there, be sure to open browser console to see the console.log');
$jaxonResponse->script("console.log('Hello there')");
return $jaxonResponse;
}
function demo2(){
$jaxonResponse = new Response();
// <div id="theDiv"> this will be replaced </div>
$jaxonResponse->assign("theDiv","innerHTML",'Some content that can even be a template if you implement smarty or similar');
return $jaxonResponse;
}
/**
* check out https://github.com/jaxon-php/jaxon-js/issues/15
* this should work, take a look at the link provided
* also use the browser console to look the response data being returned
*/
function functionThatReturnsUsing_setReturnValue(){
$jaxonResponse = new Response();
// lets suppose you have a script like this
// <script>
// function demo3(){
// var myData = jaxon_functionThatReturnsUsing_setReturnValue();
// console.log(myData);
// }
// </script>
$someData = array(
'isValidated' => TRUE,
'str_data' => 'some data here',
'int_data' => 123,
'flt_data' => 1.23,
'row_data' => array(
'isValidated' => TRUE,
'str_data' => 'some data here',
'int_data' => 123,
'flt_data' => 1.23
)
);
$jaxonResponse->setReturnValue($someData);
$jaxonResponse->getOutput();
return $jaxonResponse;
}
if($jaxon->canProcessRequest()){
$jaxon->processRequest();
}
/**
* if you are using composer, then your composer.json should have this at least:
*
* {
* "require": {
* "jaxon-php/jaxon-core": "^3.2",
* "jaxon-php/jaxon-js": "^3.2"
* }
* }
*
*/
?>
<!DOCTYPE html>
<html lang="es">
<head>
<title>Demo jaxon</title>
<?php echo $jaxon->getCss(); ?>
</head>
<body>
<ul>
<li>demo fn 1</li>
<li>demo fn 2</li>
<li>demo fn 3</li>
</ul>
<div id="theDiv">this will be replaced</diV>
<script>
function demo3(){
var myData = jaxon_functionThatReturnsUsing_setReturnValue();
console.log(myData);
}
</script>
<?php
echo $jaxon->getJs();
echo $jaxon->getScript();
?>
</body>
</html>

Auto Completion Ajax laravel

Hello I need to do autocompletion to some cities i already have in my db
so my code is like this :
View
<input type="text" name="ville" id="ville" class="small" placeholder="Entrer la ville souhaité">
<script type="text/javascript">
$(function() {
$( "#ville" ).autocomplete({
source:'{!!URL::route('autocomplete')!!}',
minlength:1,
autoFocus:true,
select:function(e,ui)
{
$('#ville').val(ui.item.value);
}
});
});
</script>
Controller
class VilleController extends Controller
{
public function autocomplete(Request $request)
{
$term = $request->term;
$queries = DB::table('ville')
->where('libelle_ville', 'like', '%'.$term.'%')
->take(6)->get();
foreach ($queries as $query)
{
$results[] = ['id' => $query->id, 'value' => $query->libelle_ville]; //you can take custom values as you want
}
return response()->json($results);
}
}
Routes
Route::get('/autocomplete', array('as' => 'autocomplete', 'uses'=>'VilleController#autocomplete'));
It doesn't tells me that I have an error and it doesn't show me any completion either.
Debug json request with laravel is a bit difficult, I recommend you to download this package
https://github.com/ARCANEDEV/LogViewer
or manually open the laravel log in storage/logs/laravel.log and see whats happened
Thanks to Stack and EddyTheDove I found out that the error is that aucomplete is not a function so I have to remove the barkets and $function so it would be something like this in the script tag
<script type="text/javascript">
$( "#ville" ).autocomplete({
source:'{!!URL::route('autocomplete')!!}',
minlength:1,
autoFocus:true,
select:function(e,ui)
{
$('#ville').val(ui.item.value);
}
});
</script>

Keeping modal dialog open after validation error laravel

So basically I have a blade.php, controller page and a form request page(validation). I'm trying to keep my modal dialog open if there is an error but I just cant figure it out, what part of code am I missing out on or needs to be changed?
blade.php
<div id="register" class="modal fade" role="dialog">
...
<script type="text/javascript">
if ({{ Input::old('autoOpenModal', 'false') }}) {
//JavaScript code that open up your modal.
$('#register').modal('show');
}
</script>
Controller.php
class ManageAccountsController extends Controller
{
public $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function index()
{
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function register(StoreNewUserRequest $request)
{
// process the form here
$this->userRepository->upsert($request);
Session::flash('flash_message', 'User successfully added!');
//$input = Input::except('password', 'password_confirm');
//$input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.
return redirect()->back();
}
}
class UserRepository {
public function upsert($data)
{
// Now we can separate this upsert function here
$user = new User;
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->mobile = $data['mobile'];
$user->role_id = $data['role_id'];
// save our user
$user->save();
return $user;
}
}
request.php
class StoreNewUserRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
// create the validation rules ------------------------
return [
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the user table
'password' => 'required|min:8|alpha_num',
'password_confirm' => 'required|same:password', // required and has to match the password field
'mobile' => 'required',
'role_id' => 'required'
];
}
}
Laravel automatically checks for errors in the session data and so, an $errors variable is actually always available on all your views. If you want to display a modal when there are any errors present, you can try something like this:
<script type="text/javascript">
#if (count($errors) > 0)
$('#register').modal('show');
#endif
</script>
Put If condition outside from script. This above is not working in my case
#if (count($errors) > 0)
<script type="text/javascript">
$( document ).ready(function() {
$('#exampleModal2').modal('show');
});
</script>
#endif
for possibly multiple modal windows you can expand Thomas Kim's code like following:
<script type="text/javascript">
#if ($errors->has('email_dispatcher')||$errors->has('name_dispatcher')|| ... )
$('#register_dispatcher').modal('show');
#endif
#if ($errors->has('email_driver')||$errors->has('name_driver')|| ... )
$('#register_driver').modal('show');
#endif
...
</script>
where email_dispatcher, name_dispatcher, email_driver, name_driver
are your request names being validated
just replace the name of your modal with "login-modal". To avoid error put it after the jquery file you linked or jquery initialized.
<?php if(count($login_errors)>0) : ?>
<script>
$( document ).ready(function() {
$('#login-modal').modal('show');
});
</script>
<?php endif ?>

Resources