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

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.

Related

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>

how to call data from laravel mailable in a view

I have a mailable class that sends an email to someone that makes a contract. Now I'm trying to style the mail but... I can't quite seem to call the variable that I pass in the mailable class return.
I've tried passing it to the view in the mailable class and I've tried calling it but in the mail it doesn't show up.
this is my mailable class:
public function build()
{
$data = array(
'comapny' => $this->data['company'],
'file' => $this->data['file'],
'subject' => $this->data['subject'],
'email' => $this->data['email']
);
foreach($data['email'] as $mail)
return $this->view('mails.contract')->with('data' , $data['company'])->to($mail)->subject($data['subject'])->attach($data['file'])->withSwiftMeassage(function ($message){
$swiftMessage = $message->getSwiftMessage();
$headers = $swiftMessage->getHeaders();
$headers->addTextHeader('From', 'example - contract <example-email#gmail.com>');
$headers->addTextHeader('Reply-To', 'example-email#gmail.com');
$headers->addTextHeader('X-Mailer:', 'PHP/' . phpversion());
});
}
}
the view i need to call the data to:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p><?php echo $data ?></p>
</body>
</html>
any help is appreciated
You need to use with() with arrays.
Replace ->with('data' , $data['company']) with ->with(['data' => $data['company']])
If you are returning a view to render data for the mail template (in this case i suppose its mails.contract template), do you have a blade template that is located in resources/mails/ and named contract.blade.php?
https://laravel.com/docs/5.8/mail#configuring-the-view
https://laravel.com/docs/5.8/mail#view-data
You can pass a variable into the mailable class like.
Need to create a constructor and define a public function.
public $data;
public function __construct( $parameter )
{
$data = /*Your logic define here and assign to `$this->data`*/
$this->data = $data;
}
public function build()
{
return $this->view('mails.contract')->with(['data' => $this->data])
->to($mail)->subject($this->data['subject'])
->attach($this->data['file'])
->withSwiftMeassage(function ($message){
$swiftMessage = $message->getSwiftMessage();
$headers = $swiftMessage->getHeaders();
$headers->addTextHeader('From', 'example - contract <example-email#gmail.com>');
$headers->addTextHeader('Reply-To', 'example-email#gmail.com');
$headers->addTextHeader('X-Mailer:', 'PHP/' . phpversion());
});
}
any public property defined on your mailable class will automatically be made available to the view.

Pass data from controller to view into script - LARAVEL

I need to pass a variable from the controller to the view, to use it in the script and configure the Highstock graph. I have a problem with the date conversion, and the use of arrays. Unfortunately, the data are not included in the chart.
I receive the data correctly in the view, but I think we need to "format" it via json_encode or whatever.
Can you tell me why and how can I solve the problem?
statistiche.blade.php
#section('content')
<div id="container" style="height: 400px; min-width: 310px"></div>
#stop
#section('css')#stop#section('js')
<script>
var data = [#php echo $data #endphp];
// Create the chart
Highcharts.stockChart('container', {
rangeSelector: {
selected: 1
},
title: {
text: 'Richieste ricevute'
},
series: [{
name: 'Richieste ricevute',
data: data,
tooltip: {
valueDecimals: 2
}
}]
});
</script>
#stop
statisticheController.php
public function index(){
/* calcolo il totale delle richieste ricevute */
$richieste = Richiesta::groupBy(DB::raw('DATE_FORMAT(created_at, "%Y-%m-%d")'))
->select(DB::raw('DATE_FORMAT(created_at, "%Y-%m-%d") as data'), DB::raw('count(*) as richieste_totali'))
->get();
foreach($richieste as $richiesta) {
$data[] = [$richiesta->data, $richiesta->richieste_totali];
}
return view('layouts.statistiche', compact( 'data'));
}
Instead of
var data = [#php echo $data #endphp]
you can just have
var data = #json($data);
Also, instead of running #php echo $stuff; #endphp you can also echo stuff like {{$stuff}}
Check this docs https://laravel.com/docs/5.6/blade

Laravel Echo not receiving Pusher notifications in realtime - ideas?

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

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