mercredi 8 septembre 2021

Adding some If/Else logic inside of rendered

I'm fairly new to VueJS. I'm using PusherBeams to send Notifications to a user, but locally and on my staging site, they're not setup as https or a localhost instance.

So what I'm thinking of doing is using my .env files to determine whether or not to load the Beamsclient

As when running locally, beams is throwing an error :

Error: Pusher Beams relies on Service Workers, which only work in secure contexts. Check that your page is being served from localhost/over HTTPS

I am wondering if I can write an IF to use the .env around the beamsClient constant that I'm setting.

Current code is :

<script>
import AppButton from '../components/AppButton';
import AppHeader from '../components/AppHeader';
import AppBackground from "../components/AppBackground";
import ColumnContainer from "../layouts/ColumnContainer";
import * as PusherPushNotifications from "@pusher/push-notifications-web";

const beamsClient = new PusherPushNotifications.Client({
    instanceId: 'sasasa',
});

beamsClient
    .start()
    .then(() => beamsClient.addDeviceInterest('club'))
    .then((beamsClient) => beamsClient.getDeviceId())
    .then((deviceId) =>
        console.log("Successfully registered with Beams. Device ID:", deviceId)
    )
    .catch(console.error);

export default
{
    components: {ColumnContainer, AppButton, AppHeader, AppBackground},
    props: ['user']
};
</script>


via Chebli Mohamed

mardi 7 septembre 2021

Call laravel controller from vue file

I created a component in vue file and I want to fetch data from laravel controller function.

currently, I have used axios to fetch data. But can I directly call laravel controller function?

Thanks in advance.



via Chebli Mohamed

Laravel undefined uPlot library

I'm trying to use the library uPlot into my view. But I'm getting an error of Uncaught ReferenceError: uPlot is not defined it seems that it can't find the uPlot library but this library is already loaded in the bootstrap as shown below

// resources/js/bootstrap.js

window._ = require('lodash');
try {
    window.Popper = require('popper.js').default;
    window.$ = window.jQuery = require('jquery');

    require('bootstrap');
    require('admin-lte');

    require('../../node_modules/uplot/dist/uPlot.iife.min');

} catch (e) {}

Now the chart.js is loaded in the resource/js/app.js as shown below

require('./bootstrap');
require('./chart');

Now in my chart.js I have this

$(function () {

    function getSize(elementId) {
        return {
          width: document.getElementById(elementId).offsetWidth,
          height: document.getElementById(elementId).offsetHeight,
        }
      }

  let data = [
    [0, 1, 2, 3, 4, 5, 6],
    [28, 48, 40, 19, 86, 27, 90],
    [65, 59, 80, 81, 56, 55, 40]
  ];

  const optsLineChart = {
    ... getSize('lineChart'),
    scales: {
      x: {
        time: false,
      },
      y: {
        range: [0, 100],
      },
    },
    series: [
      {},
      {
        fill: 'transparent',
        width: 5,
        stroke: 'rgba(60,141,188,1)',
      },
      {
        stroke: '#c1c7d1',
        width: 5,
        fill: 'transparent',
      },
    ],
  };

  let lineChart = new uPlot(optsLineChart, data, document.getElementById('lineChart'));
  window.addEventListener("resize", e => {
    lineChart.setSize(getSize('lineChart'));
  });
});

Now the element lineChart is already defined but it's throwing an error when the script reaches the line new uPlot. I checked the pub/js/app.js and the uPlot was successfully imported. As well as the chart.js is included in the app.js. But one this I noticed is the script of chart.js is added at the very top of the app.js file while the uPlot is added at the bottom part.

How can I fix this? It doesn't seem like the uPlot library is being read or loaded in the chart.js file



via Chebli Mohamed

Problem with javascript and laravel - Save token

i am working with push notifications, i need to save the token it generates and pass it through POST

Javascript:

 function pedirPermiso(){
    messaging.requestPermission()
    .then(function(){
        console.log("Se han haceptado las notificaciones");
        hideAlert();
        return messaging.getToken();
    }).then(function(token){
        console.log(token);
        guardarToken(token);
    }).catch(function(err){
        console.log('No se ha recibido el permiso');
        showAlert();
    });
}
function guardarToken(token){
    var formData=new FormData();
    formData.append('token',token);
    axios.post('/token',formData).then( respuesta=>{
        console.log(respuesta);
    }).catch( e=>{
        console.log(e);
    });
}

Route:

Route::post('/token', 'savetoken@HomeController' )->name('token');

Controller:

     public function savetoken()
{
        Notificaciones::insert([
          'user_id'  => 1,
          'token'        => ("token")
        ]);
  
        return back()->with('success', 'token saved successfully!');
}

Error in console: https://i.imgur.com/BfH0Onk.png

how to save the token correctly?



via Chebli Mohamed

lundi 6 septembre 2021

The filtered result I get by running the filter method on a laravel collection returns a new collection with an undesired index

To make it easier to understand the problem, I will hardcode the data that I am using the collection on and explain the problem.

Let us assume the following data structure in JSON format,

{
"shelters_with_linear_distances": [
    {
        "id": 3,
        "shelterName": "Third Shelter",
        "latitude": "5.0034000",
        "longitude": "70.1230000",
        "linear_distance": 3.1352984845527
    },
    {
        "id": 4,
        "shelterName": "Fourth Shelter",
        "latitude": "5.1413000",
        "longitude": "70.2250000",
        "linear_distance": 2.7850629146201
    },
    {
        "id": 5,
        "shelterName": "Fifth Shelter",
        "latitude": "5.2220000",
        "longitude": "70.1320000",
        "linear_distance": 2.6042789457753
    }
]
}

The following filter method is run on a collection format of 'shelters_with_linear_distance' in the above data structure and $minimum_distance_to_a_shelter is a dynamically calculated value that holds a data type of double.

$nearest_shelter = $shelters_with_linear_distances_from_user
    ->filter(function ($shelter, $key) use ($minimum_distance_to_a_shelter) {
        return $shelter['linear_distance'] == $minimum_distance_to_a_shelter;
    });

The problem here is if I send back the value returned by the filter method (which is the $nearest_shelter) as JSON to the frontend, in the postman I see the following output,

{
    "nearest_shelter": {
        "2": {       // <------------------------------------ I can not figure out from where this key '2' is coming from.
            "id": 5,
            "shelterName": "Fifth Shelter",
            "latitude": "5.2220000",
            "longitude": "70.1320000",
            "linear_distance": 2.6042789457753
        }
    }
}

The problem is I can not figure out from where the key I have pointed with an arrow in the above line of code is coming from. *) It is okay if that value '2' never changes so that in the later parts of code I can always access the $nearest_shelter as $nearest_shelter['2']. But the problem is, the value of that key changes depending on the data I am receiving from the db.

One time that value of the key was '1', then once I added some new records to the db it was '2'. Also this one other time there was no key marked as either '1' or '2' and the shelter I wanted was directly inside the collection.

Can someone please help me understand why this is happening and how to get rid of that since I want to access the value inside the $nearest_shelter in latter parts of the code and I do not want to get a key like that which I do not know the value of beforehand to access the $nearest_shelter later in the code.

(Project I am working on uses laravel 5.2)

Thanks.



via Chebli Mohamed

Laravel Eloquent filter by MySQL Timestamp

I have a Laravel (5.2) Eloquent Model where the database field type is MySQL Timestamp and having values in Y-m-d H:i:s format,

I am wiring some Laravel Eloquent model as:

UserSubscription::where('renewal_date','<=',Carbon::now());

but when I print this using toSql() , the query print ? instead Carbon::now() value, I tried below options:

  1. Carbon::now('UTC') I already have timezone defined in my config file as UTC.

  2. Carbon::now()->format('Y-m-d H:i:s')

but nothing worked, where and what I am doing wrong..?



via Chebli Mohamed

Error retrieving credentials from the instance profile metadata service. we are getting "Aws \ Exception \ CredentialsException

enter image description hereI have installed "aws/aws-sdk-php": "^3.180" package in laravel also updating an IAM role variable in ENV file we are getting "Aws \ Exception \ CredentialsException Error retrieving credentials from the instance profile metadata service. (cURL error 28: Connection timed out after 1010 milliseconds (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for http://169.254.169.254/latest/meta-data/iam/security-credentials/)" exception. we want to upload images in the s3 bucket using the AWS IAM role.

enter image description here



via Chebli Mohamed