Gabotronix

Gabotronix

Member Since 2 Years Ago

Experience Points
28,790
Total
Experience

1,210 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
45
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 6
28,790 XP
Sep
19
22 hours ago
Activity icon

Started a new Conversation PHP: Remove All Characters From String After X Occurrences Of A Character

Hi everybody, I'm trying to remove all the characters of a string AFTER a character appears 4 times, in this case the fourth appearance of character "/".

So if I have a string like this:

https://www.imbd.com/zenithasianfancyfood/posts

I want to get something like:

https://www.imbd.com/zenithasianfancyfood/
Activity icon

Replied to False Positive With Email Regex

How can I do that?

Activity icon

Started a new Conversation False Positive With Email Regex

Hi everybody, I'm using regex and match to grab all emails in an HTML string, however I'm getting false positives, how can I improve my regex (I'm not very good at it), I'd like to add something like "ends in .com" so I don't grab any false matches.

const emailRegex = /([\s]*)([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*([ ]+|)@([ ]+|)([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,}))([\s]*)/ig;
let emailsInFacebook = bodyHTML.match(emailRegex); 

This gives me an array with false positives like this one:

emails: 
{
  '0': '[email protected]',
  '2': '[email protected]',
  '3': '[email protected]'
}
Sep
18
1 day ago
Activity icon

Started a new Conversation Issue Grabbing All Emails From DOM String With Match And Regex

Hi everybody, I'm trying to extract all emails from a DOM html string using regex and javascript match but I'm getting null, is it because of my regex or the string I'm using to test it?

var bodyHTML = '<header><div><a href="mailto:[email protected]"></a></div></header><a href="mailto:[email protected]"></a>';

        var emailRegex = new RegExp("/([\s]*)([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*([ ]+|)@([ ]+|)([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,}))([\s]*)/i", "g");
        var results = bodyHTML.match(emailRegex); 
        console.log(results);

Thanks in advance!

Sep
17
2 days ago
Activity icon

Started a new Conversation Puppeteer.js : Get Href Attribute Of Link With Given Text

Hi everybody, is there a way in puppeteer to get the href attribute of an anchor element with text "See more".

I want to grab the href attribute of an element like this:

<a href="/this-is-what-i-want">See more</a>

maybe it's possble to do with eval?

Activity icon

Started a new Conversation Why Can't I Use Import/export In Node.js Enviroment?

Hi everybody, I'm working in my first node.js app coming from a vue/laravel background where I alsways used import/exports, now I'm trying to use it in my node.js but I get the following error:

(node:13072) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
C:\xampp\htdocs\myapp\app.js:7
import MapsService from '../services/MapsService';
^^^^^^

SyntaxError: Cannot use import statement outside a module

I thought node.js was pretty common, how can I not use import/exports? This is what I have in my app.js

var express = require('express');
var app = express();
//process.env.DB_HOST
require('dotenv').config()


import MapsService from '../services/MapsService';

app.get('/', async (req, res) => {

    MapsService.scrapeAddress();

    res.send('Hello World!');
});


app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

And in my MapsService file I use imports/exports too, does that mean I will have to use this require thing I see? How can I transform my MapsService file to be require friendly?

//import { Client } from '@googlemaps/google-maps-services-js';
import * as geometry from 'spherical-geometry-js';
import axios from "axios";
//const axios = require('axios').default ??;
import VenuesService from '../services/VenuesService';


export class MapsService {

   



}
Activity icon

Started a new Conversation Using Google Places API In Node.js Server Enviroment

Hi everybody, this is my first node.js application where I will be using javascript in the server, previously I used google places API javascripe in the client, like this:

async codeAddressFromList(address)
    {
        const self = this;
        this.address = address;
    
        return self.geocoderService.geocode( { 'address': address}, function(results, status)
        {
            if (status == 'OK')
            {
                self.map.setCenter(results[0].geometry.location);
                self.calculateNewSquareVertex(results[0].geometry.location);
                self.drawRects();
            } 
            else
            {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    },

I was wondering what's the best way to use google places API in node.js.

Since node is javascript in the server will I be able to use the javascript API in the server? I have seen some people using axios to make requests and using query strings, I have also found about this library:

https://github.com/googlemaps/google-maps-services-js

But I'm not sure about suing a lib, what is the more vanilla, battle tested way to do this?

Can you guys post some of your node.js google places API examples?

Sep
16
3 days ago
Activity icon

Started a new Conversation Preg_match_all Equivalent In Javascript?

Hi everybody, I want to grab all emails inside a DOM string I get like this:

document.documentElement.outerHTML

I have the following regex from an old PHPproject:

"/([\s]*)([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*([ ]+|)@([ ]+|)([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,}))([\s]*)/i"

How can I check for all matches in the whole html string? preferably pushing each match into an array would be best!

Sep
15
4 days ago
Activity icon

Started a new Conversation Keep Facebook Login Session With PHP Puphpeteer?

Hi everybody, I'm using puphpeteer which is a PHP bridge for node's puppeteer supporting the whole API, I will be scraping different facebook pages looking for some info, for this I have to login with my credentials and then go to targeted facebook page.

My objective is to ONLY LOG INONE TIME and than once logged, use facebook session/log in cookies to keep my session for subsequent urls, afaik this would be possible to do but I haven't found any examples on how to do this with PHP Puphpeteer.

Here is my code:

use Nesk\Puphpeteer\Puppeteer;
use Nesk\Rialto\Data\JsFunction;
use Nesk\Puphpeteer\Resources\ElementHandle;


public function scrapeFacebookForBirthdays()
    {
        $cookies = null;

        $puppeteer = new Puppeteer();
        $browser = $puppeteer->launch([ 'headless' => false, 'slowMo' => 250 ]);
        $browser->setUserAgent('Opera/9.80 (Windows NT 6.2; WOW64) Presto/2.12.388 Version/12.17');

        $page = $browser->newPage();

        
        //Check if cookies are set or not, if not set it means we have to log in ONCE, but HOW to cjeck for cookies, where to save them?
        if (!$cookies)
        {
            $page->goto("https://www.facebook.com/login", [ 'waitUntil' => "networkidle2" ]);
            $page->type("#email", $username, [ 'delay' => 30 ]);
            $page->type("#pass", $password, [ 'delay' => 30 ]);
            $page->click("#loginbutton");

            sleep(5);

            $page->waitForNavigation([ 'waitUntil' => "networkidle0" ]);

            try 
            {
                echo "success login";
                $page->waitFor('[data-click="profile_icon"]');
            }
            catch (Exception $e)
            {
                echo "failed to login";
                $browser->close();
            }

            //Where to save cookies for next url scrape??
            $cookies = $page->cookies();
        }
        else
        {
            //User Already Logged In
            $page->setCookie($cookies);
        }
    }

Thanks in advance!

Sep
11
1 week ago
Activity icon

Started a new Conversation PHP: Check For Last Instance Of Substring Inside String And Remove All Characters Before

Hi everybody, I want to check for each instance of substring "http" inside a string, and for the last instance of it I want to remove all characters before it excluding the substring, so for example for the given string:

"http://www.google.es/url?q=https://www.facebook.com/lacamperiamlg/&sa=U&ved=2ahUKEwjFkKOrxeHrAhXFFogKHa5nAI8QgU96BAgMEAQ&usg=AOvVaw2opxQ32h4Yg5LdpJLYjS6J"

Where there are two instances of "http", I would remove all characters prior to the last instance of "http", I'd have the following result:

https://www.facebook.com/lacamperiamlg/&sa=U&ved=2ahUKEwjFkKOrxeHrAhXFFogKHa5nAI8QgU96BAgMEAQ&usg=AOvVaw2opxQ32h4Yg5LdpJLYjS6J"

How can I do this with PHP?

Sep
08
1 week ago
Activity icon

Started a new Conversation Remove Objects From Array Comparing With Another Array

Hi everybody, I have an array blackList where I store blacklisted business names, now I have a results array of objects with many business, I want to store in an array the business names which are not included in the blackListed array, what is the easier and most performant way to do this?

Is a nested loop really needed for this?

blackList = [ "Dominos Pizza", "Domino's Pizza", "McDonald's", "McDonalds",  "Telepizza", "Subway", "Burger King", "KFC", "Pans&Co", "Pans&Company" ,
        "Rodilla", "Rodilla Campamento", "Granier", "Llaollao" , "Taco Bell", "Wendy's", "Dunkin' Donuts", "Pizza Hut", "Papa John's Pizza", "Little Caesars",
        "Panera Bread", "Chipotle", "Papa Murphy's", "Hungry Howie", "Chipotle Mexican Grill", "Starbucks"],
        list = [ { name:'business 1' }, { name:'business 2' }, { name:'business 3' } ]
Activity icon

Started a new Conversation Setting User Agent Header With Goutte/Guzzle? (undefined Method Error)

I'm trying to set user-agent in Goutte, I'm using setHeader but I get undefined method setHeader error in console.

Call to undefined method Goutte\Client::setHeader()

How can I set user-agent header in Goutte?

public function getGoogleResults(Request $request)
    {
        $terms = 'Nata & Chocolate Gluten Free Bakery';//$request->input('terms');
        $url = 'http://www.google.es/search?'.http_build_query(array('q' => $terms));
        
        $client = new Client;
        $client->setHeader('user-agent', "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36");
        $crawler = $client->request('GET', $url);
}
Activity icon

Started a new Conversation Difference Between Local Business And Big Franchise Business In Google Places API Results?

Hi everybody, when I use Google Places API to retrieve local business info, for example using nearbySearch in the javascript enviroment, is there a way to differenciate between big franchise business like Pizza Hut and a local business like Arno's Pizza?

Sep
06
1 week ago
Activity icon

Started a new Conversation Is It Possible To Send A Facebook Friend Request Using Pupeteer.js?

I was wondering if it's possible to do so? what about a direct message, or automating my posts on my fb page? I can succesfully login with my facebook credentials using pupeteer.js which afaik simulates a browser (or headless browser?).

What are the limitations of pupeteer.js, apart from doing javascript (Goutte PHP lib can't do js sadly), is it possible to do with pupeteer.js anything you can do with normal user - laptop/pc interaction?

Activity icon

Started a new Conversation Issue Using Goutte Filter Method To Crawl DOM For Google Links

Hi everybody, I want to use Goutte for getting the first result links of a google search, in order to get the links I have to use Goutte filter method and css-like selectors, I want to grab all the anchor elements which are first child of div element with class r, as you can see in image bellow all result links follow that pattern.

https://i.imgur.com/hnaSRdb.png

However when I loop through filtered elements I get nothing, any idea why is this?

$terms = 'Restaurante Mustang';//$request->input('terms');
        
        $url = 'http://www.google.es/search?'.http_build_query(array('q' => $terms));
        
        // Request search results:
        $client = new Client;
        $crawler = $client->request('GET', $url);


        $links = $crawler->filter('div.r > a');

        $nodes = [];
        foreach ($links as $index => $link)
        {	
            $nodes[] = $link; 
        }
        dd($nodes);

Is it because my selectors are wrong?

Sep
05
2 weeks ago
Activity icon

Started a new Conversation Get Google Search First Result With Goutte

Hi everybody, I want to get the first result url of google search using Goutte PHP library, sadly I haven't found many info on how to get a list of results from google using Goutte...

I'm using laravel and I already installed Guzzle and Goutte libraries with composer.

public function getGoogleResults(Request $request)
    {
        // Extract and sanatize input:
        $domain = $request->input('domain');
        $terms = $request->input('terms');
        
        // Build up a search URL:
        $pages = 10;
        $url = 'http://www.google.es/search?'.http_build_query(array('q' => $terms));
        
            // Request search results:
        $client = new Goutte\Client;
        $crawler = $client->request('GET', $url);
        
    }
Sep
02
2 weeks ago
Activity icon

Started a new Conversation Google API To Get Google Query Search Results With Laravel 6+ For Free?

I already enabled billing in my Google API services, I want to be able to use google api search in laravel to query results as if an user was to use the classic google searchbox, I want to atleast get 10 url results.

What is the best and easier composer package for doing this for free? Is such a thing even possible to do with php?

Sep
01
2 weeks ago
Activity icon

Started a new Conversation Javascript Interval Won't Stop (clearInterval Issue)

Hi everybody, I set up an interval which executes some API calls each X seconds, I will do this for the length of an array and increment a counter, esentially acting as a timed for loop, problem is the timer won't stop after reaching the length of my array, can you guys see where's the issue?

Activity icon

Started a new Conversation Handling Multiple Async Calls Inside For Loop

I have a javascript for loop where I call a function for each lat-lng bound, inside this function I execute THREE async calls to google maps Places API, after all three calls execute I color the bounds green.

Issue is my for loop executes in a sync way and all bounds are colored green in a single tick instead of aiting for all three async calls to resume.

How can I do it so the for loop waits for the async calls to execute before going to the next iteration?

My code:

async startScrapingGridLoop()
    {
        const self = this;

        for (var i = 0; i < self.zoneBoundaries.length; i++)
        {
            //Multiple async calls
            await self.scrapeCellWithPlaces(self.zoneBoundaries[i]);
            //After all three async calls end I want to color the bound green
            let currentPolygon = self.polygonsArray[i];
            currentPolygon.setOptions({fillColor: 'green', fillOpacity:0.6});

        }
    },

async scrapeCellWithPlaces(zoneBoundaries)
    {
        const self = this;
        var request = {};
        var bounds = new google.maps.LatLngBounds(new google.maps.LatLng({ lat:zoneBoundaries.sw.lat(), lng:zoneBoundaries.sw.lng() }), new google.maps.LatLng({ lat:zoneBoundaries.ne.lat(), lng:zoneBoundaries.ne.lng() }));


        for (var i = 0; i < self.types.length; i++)
        {
                
                
            request = { bounds: bounds, type: self.types[i] };
                
            self.placesService.nearbySearch(request, self.scrapeCellWithPlacesCallback);
            console.log('Scraping bounds for '+self.types[i]);
        }

    },

scrapeCellWithPlacesCallback(results, status, pagination)
    {
        const self = this;
         
        if (status == google.maps.places.PlacesServiceStatus.OK)
        {      
            for (var i = 0; i < results.length; i++)
            {
                self.results.push(results[i]);
            } 

            //self.setPlacesMarker(self.results);
            //self.fitPlacesBounds(self.results);
            
            if (pagination.hasNextPage)
            {
                console.log('fetching next set of sets');
                sleep:3;
                pagination.nextPage();

                for (var i = 0; i < results.length; i++)
                {
                    self.results.push(result[i]);
                } 
            }
        }
        console.log(self.results);
    },

Aug
31
2 weeks ago
Activity icon

Started a new Conversation Laravel: Check If Model Property Already Exists Before Uploading Into DB Using Eloquent, Performance Issues

I have a huge ammount of records I want to upload into mysql database in my laravel app, in order to avoid uploading duplicates I want to check if name there is already a model in database with the same name, I'm doing this check with Eloquent but given I'll be handling large ammount of data I was wondering if there is a more performant way to do this, my objective is to perform the less DB operations possible!

My code:

public function uploadIntoDatabase(Request $request)
    {
        $venuesToUpload = $request['venuesToUpload'];

        $allVenues = Venue::all();

        foreach($venuesToUpload as $index => $venue)
        {
            $alreadyAdded = Venue::where('name', $venue['name'])->first();

            if(!$alreadyAdded)
            {
                $newVenue = new Venue();
                $newVenue->name = $venue['name'];
                $newVenue->save();
            }
        }

        return response()->json([
            'message' => 'All venues uploaded',
        ]);
    }

Help me out please!

Aug
30
2 weeks ago
Activity icon

Started a new Conversation How Many Google Places Search/Details Requests Per Day Can I Make For Free?

I have enabled billing for my Google Places API credentials, I'm using Javascript SDK, after reading the docs on usage and billing I'm even more confused, I don't want to have a surprise 2k ticket this month just because I exceeded the limits so can anyone explain to me:

How many Place Search request requests per day can I make?

How many Place Details requests per day can I make?

For Foursquare API they are much straightfordward with limit usage, I have 5000 premium and 95000 basic requests per day, easy right? For places it seems they tried to make the docs as vague as possible in order to cash in.

Usage and billing: https://developers.google.com/places/web-service/usage-and-billing

Aug
28
3 weeks ago
Activity icon

Started a new Conversation How To Deal With Google Maps API Calls Inside A For Loop

Hi everybody, I have an array of rectangular boundaries which I want to search for restaurants with Google Places API javascript.

At first I thought about iterating through boundaries array with for loop, issue is in each iteration I'll be making an async API call and for loop is sync action...

Ideally I'd like to iterate through all boundaries with a one minute difference between each API call and finish once all boundaries have been search, maybe with setInterval but I can't quite get my grap around how I 'd deal with this?

How can I do this?

loopSearch(zoneBoundaries)
    {
        for (var i = 0; i <= zoneBoundaries.length; i++)
        {
            const self = this;

            var bounds = new google.maps.LatLngBounds(
                new google.maps.LatLng(zoneBoundaries[i].sw),
                new google.maps.LatLng(zoneBoundaries[i].ne)
            );

            self.placesService = new google.maps.places.PlacesService(self.map);

            var request = { bounds: bounds, types: [ 'restaurant', 'bar'] };

            self.placesService.search(request, self.placesCallback);
        }
    },
Aug
27
3 weeks ago
Activity icon

Started a new Conversation Change Google Maps Polyline Grid Background Color?

I can create a grid using google maps polyline, now I'd like to change the color of a given cell, problem is I don't know how to select or define cells, how to iterate through them or maybe on click select a given cell.

Here is the code for creating grid lines with polyline:

http://jsfiddle.net/geocodezip/8z38L0o0/1/

How can I select grid cells and change color/hilight them?

Activity icon

Started a new Conversation Draw Google Maps Grid Always In The Same Place?

Hi everybody, I can create a grid of cells inside a given boundary in google maps, the priblem is I want this grid overlay to be always the same! no matter where my bounds are/start, I use polylines to create the greed as you can see in code bellow.

http://jsfiddle.net/geocodezip/8z38L0o0/1/

Is it possible to do? will the grid cells always hold the same latitudes and longitudes? This is important becuase I want the overlay to always be the same.

Activity icon

Started a new Conversation Get Coordinates Of Drawn Rectangle In Google Maps

Hi everybody, I got the code to draw a draggable rectangle in google maps

https://jsbin.com/harawira/1/edit?html,js,output

I know I can get the coordinates of a rectangle by its bounds like in code bellow but in my drawing code I don't have a reference to the drawn rectangle, how can I get NE and SW of a drawn rectangle?

var bounds = rectangle.getBounds();
var NE = bounds.getNorthEast();
var SW = bounds.getSouthWest();
// North West
var NW = new google.maps.LatLng(NE.lat(),SW.lng());
// South East
var SE = new google.maps.LatLng(SW.lat(),NE.lng());
Activity icon

Started a new Conversation Avoid Google Places API Expanding Boundaries

Hi everybody, I'm using goole places javascript API to search for establishements inside a boundary, sometimes google places will expand its search radius and I want to avoid this behaviour, is this possible?

My search query has a bounds filed (a pair of lat-lng coordinates) where I want google places to search ONLY inside this boundary... is there like a flag or something to avoid this behaviour?

search()
    {
        const self = this;

        var bounds = new google.maps.LatLngBounds(
            new google.maps.LatLng(36.715289, -4.423523),
            new google.maps.LatLng(36.717387, -4.422407)
        );

        self.placesService = new google.maps.places.PlacesService(self.map);
        
        //var request = { placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4', fields: ['name', 'rating', 'formatted_phone_number', 'geometry']};
        var request = { bounds: bounds, types: ['restaurant', 'bakery', 'cafe', 'food', 'meal_takeaway', 'bar', 'meal_delivery'] };

        //const request = {query: "Restaurants in Malaga",fields: ["name", "geometry"]};

        self.placesService.search(request, self.placesCallback);
        //self.placesService.findPlaceFromQuery(request, self.placesCallback);
        //places.getDetail
        
    },
Activity icon

Started a new Conversation Google Places API Not Returning All Restaurants Inside Bounds (not Even Close)

Hi everybody, I'm using Google Places Javascript API in order to return all restaurants and food related places inside a small rectangular bound, issue is I'm getting 10-14 places inside area but there should be much more, according to docs I can get up to 60 results split in three batches of 20 results, so why am I getting so few results?

I this because the clients SDK are limited, should I use the backend SDK instead? My objective is to retrieve all restaurants in a city, I want to do this by splitting the map in a grid and searching each cell, but sadly I'm not getting accurate results at all...

This is my code:

search()
    {
        const self = this;

        var bounds = new google.maps.LatLngBounds(
            new google.maps.LatLng(36.720054, -4.405126),
            new google.maps.LatLng(36.721490, -4.404268)
        );

        self.placesService = new google.maps.places.PlacesService(self.map);
        

        var request = { bounds: bounds, types: ['restaurant', 'bakery', 'cafe', 'food', 'meal_takeaway', 'bar', 'meal_delivery'] };

        self.placesService.search(request, self.placesCallback);
        
    },

placesCallback(results, status, pagination)
    {
        const self = this;
        // process the resutls  
        if (status == google.maps.places.PlacesServiceStatus.OK)
        {      
            //console.log(results);
            self.results = results;

        }
    },
Aug
26
3 weeks ago
Activity icon

Started a new Conversation Vue: Grab South/west And North/east Lat-lng From Polyline Grid In Google Maps

Hi everybody, I have a code which draws a grid using polylines in a map, you can check code bellow. What I want to do is grab all grid cells' south/west and north/east latitude and longitude pair into an array, see image bellow:

https://i.imgur.com/6seWdli.png

I want to store each pair inside an array like this:

[
    [ { lat:44.648490, lng:44.774844 }, { lat:46.648490, lng:46.774844 } ],
    [ { lat:44.648490, lng:44.774844 }, { lat:46.648490, lng:46.774844 } ],
    
    ...


]

My code: http://jsfiddle.net/geocodezip/8z38L0o0/1/

Aug
19
1 month ago
Activity icon

Started a new Conversation Transparent Radial Gradient With Image Behind?

I saw a wesite with a neat simple gradient and a partially oscured image, how can I acheive this with CSS?I guess with an absolute overlay with a radial but I'm not very good with gradient... is this masking maybe? or pure CSS?

The effect: https://i.imgur.com/WiIP5wk.png

<div style="position:relative; width:100%; height:600px; background-image:url('/background-image.jpg');>
    <div style="width:100%; height:100%; position:absolute; top:0px; left:0px;></div>
</div>
Aug
10
1 month ago
Activity icon

Started a new Conversation Stripe, Webhooks And SCA European Law Checkout Flow

Hi everybody, I'm working on a website with Stripe payments, it's europe based so I'll have to deal with SCA 3D Secure auth, stripe docs recommend me to deal with payment fulfillment asynchronously instead of waiting for confirmCardPayment promise to resolve, to accomplish this you have to use webhooks.

From the docs:

stripe.confirmCardPayment(clientSecret, {
  payment_method: {
    card: card,
    billing_details: {
      name: 'Jenny Rosen'
    }
  },
  setup_future_usage: 'off_session'
}).then(function(result) {
  if (result.error) {
    // Show error to your customer
    console.log(result.error.message);
  } else {
    if (result.paymentIntent.status === 'succeeded') {
      // Show a success message to your customer
      // There's a risk of the customer closing the window before callback execution
      // Set up a webhook or plugin to listen for the payment_intent.succeeded event
      // to save the card to a Customer

      // The PaymentMethod ID can be found on result.paymentIntent.payment_method
    }
  }
});

Notice the comment that says:

// There's a risk of the customer closing the window before callback execution
// Set up a webhook or plugin to listen for the payment_intent.succeeded event

Because of that warning I'm confused about how to deal with confirmCardPayment promise.

Should I just take the user to another page after I call confirmCardPayment from client and show the order in that new page with status: PENDING or PROCCESING.

Should I do this a few seconds after calling confirmCardPayment with a timer or check there is no error in callback, inside the else brackets of the promise callback and use location.href there to move user to see the order?

After that I would deal with order fulfillment in backend with webhooks (listen to payment_intent.succeded event, remove from stock, send order email and do remaining database operations)

If I do this would the SCA modal still show up? Stripe says Stripe.js deals with SCA and showing modal but if I redirect user to pending orde page with no stripe.js how would SCA modal action complete?

This is pretty confusing.

Activity icon

Replied to Stripe CLI Sends Webhooks With Fake Data, How Am I Supossed To Test My Integration

where can I check that, I test in my local windows machine, localhost, http and using stripe cli to fire events like payment.succeded

Activity icon

Started a new Conversation Stripe CLI Sends Webhooks With Fake Data, How Am I Supossed To Test My Integration

Hi everybody, I'm working on a website with Stripe payments, it's europe based so I'll have to deal with SCA 3D Secure auth, stripe docs recommend me to deal with payment fulfillement asynchronously instead of waiting for confirmCardPayment promise to resolve, to accomplish this you have to use webhooks.

Something I noticed is webhooks send fake data in events, if data is fake how am I supossed to actually test my integration? order fulfilment in database, other database operations, sending email with order info...

Am I missing something?

Aug
09
1 month ago
Activity icon

Started a new Conversation Instantiate Laravel Model Referenced By String

Hi everybody, I want to instantiate a laravel model given a string as reference, that is I have a string variable $model with value "User", I want to do something like:

$userInstance = new $model();

Or similar, how can I do this?

Aug
04
1 month ago
Activity icon

Started a new Conversation Laravel/Socialite: Create OAuth Google_id And Secret_key Programatically?

In my laravel app I want to implement OAuth google login with laravel/socialite, for this I have to create some google credentials, client_id and secret_id, I do this from google console, I also have to add two uris, main uri and callback uri.

Most of my laravel/vue apps use OAuth, particularly google auth so the login proccess can be easier/faster, having to create credentials for each of my web apps is such a turn off.

I was wondering if there's a way to do this setup programatically with PHP/Javascript code, is it possible?

Activity icon

Started a new Conversation Laravel: Give LongText Field A Default Value

Pretty straightforward, in laravel I can't give longText or text fields a default value, given a field named "body" where body will probably have some text or html, how can I give it a default value in mysql?

Aug
02
1 month ago
Activity icon

Started a new Conversation Stripe Webhooks. Actions To Take In The Frontend?

Hi everybody, I want to implement a payment gateway with Stripe, it will also be SCA compliant (2019 european law).

Stripe docs it says sometimes users may leave the page before confirmCardPayment callback finishes, because of this I want to implement stripe webhooks, I'm wondering about how to deal with stripe webhooks completing a transaction in an async way (user may not even be with their phone), what action should I take in the frontend while confirmCardAction is running to show the transaction was completed (or is waiting to, and this may tae several minutes/hours), showing a spinner for an infinite ammount of time seems like a bad idea to me.

What I know for sure is I will be sending an email when webhook is reveived AND proccesed but my confusion comes in how to deal with it in the frontend and user checkout flow.

Aug
01
1 month ago
Activity icon

Started a new Conversation Using Stripe CLI In Windows?

Hi everybody, I want to test stripe webhooks in my local windows dev machine, stripe docs mention stripe CLI as the best /easier way to test webhooks endpoints and sending fake events, I followed the docs to down load stripe CLI into my windows machine, I extracted the executable into my desktop but now I don't know how to properly excute commands in my cmd.

stripe.exe in my desktop, I first tried just simply clicking it, command prompt opened and showed message bellow, after a few seconds the command prompt closes.

This is a command line tool.

You need to open cmd.exe and run it from there.

After that I tried opening a CMD window and drag and dropping stripe.exe into the tab, I get the following list of commands:

C:\Users\GABRIEL>C:\Users\GABRIEL\Desktop\stripe.exe
The official command-line tool to interact with Stripe.

Before using the CLI, you'll need to login:

  $ stripe login

If you're working on multiple projects, you can run the login command with the
--project-name flag:

  $ stripe login --project-name rocket-rides

Usage:
  stripe [command]

Webhook commands:
  listen                        Listen for webhook events
  trigger                       Trigger test webhook events

Stripe commands:
  logs                          Interact with Stripe API request logs
  status                        Check the status of the Stripe API

Resource commands:
  get                           Quickly retrieve resources from Stripe
  charges                       Make requests (capture, create, list, etc) on charges
  customers                     Make requests (create, delete, list, etc) on customers
  payment_intents               Make requests (cancel, capture, confirm, etc) on payment intents
  ...                           To see more resource commands, run `stripe resources help`

Other commands:
  completion                    Generate bash and zsh completion scripts
  config                        Manually change the config values for the CLI
  feedback                      Provide us with feedback on the CLI
  fixtures                      Run fixtures to populate your account with data
  help                          Help about any command
  login                         Login to your Stripe account
  logout                        Logout of your Stripe account
  open                          Quickly open Stripe pages
  samples                       Sample integrations built by Stripe
  serve                         Serve static files locally
  version                       Get the version of the Stripe CLI

Flags:
      --api-key string        Your API key to use for the command
      --color string          turn on/off color output (on, off, auto)
      --config string         config file (default is
                              $HOME/.config/stripe/config.toml)
      --device-name string    device name
  -h, --help                  help for stripe
      --log-level string      log level (debug, info, warn, error)
                              (default "info")
  -p, --project-name string   the project name to read from for config
                              (default "default")
  -v, --version               Get the version of the Stripe CLI

Use "stripe [command] --help" for more information about a command.

C:\Users\GABRIEL>

as you see I can't type any command, something like

stripe login

I'm left with no option to do anything with stripe cli in cmd... please help me out

Jul
28
1 month ago
Activity icon

Replied to 404 Error When Testing Stripe Webhooks With Ngrok

what for, is this some lib utility, I didn't install anything and I already declared my route in api routes

Jul
27
1 month ago
Activity icon

Started a new Conversation 404 Error When Testing Stripe Webhooks With Ngrok

Hi everybody, I want to test stripe webhooks from stripe dashboard using ngrok, when I send a test webhook to my route I get error 404 response on dashboard.

In ngrok cmd tab I get this error:

HTTP Requests
-------------                                                                                                                                                                                                                                   POST /api/stripe/webhooks      404 Not Found 

In dashboard I added the following endpoint

http://daa0199bce35.ngrok.io/api/stripe/webhooks

which points to this route:

Route::post('/stripe/webhooks', 'Api\[email protected]');

In ngrok tab I get the following:

Session Status                online                                                                                    Session Expires               6 hours, 50 minutes                                                                       Version                       2.3.35                                                                                    Region                        United States (us)                                                                        Web Interface                 http://127.0.0.1:4040                                                                     Forwarding                    http://daa0199bce35.ngrok.io -> http://localhost:80                                       Forwarding                    https://daa0199bce35.ngrok.io -> http://localhost:80                                                                                                                                                              Connections                   ttl     opn     rt1     rt5     p50     p90                                                                             4       0       0.00    0.00    0.02    0.24  
Jul
26
1 month ago
Activity icon

Started a new Conversation Is There A Npm Package With V-if V-else Syntax For React-native?

Coming from vue having to use ternary operators in code seems so ugly, is there a package to use something similar to vue's conditional rendering with v-if and v-else to put in react native JSX

Jul
25
1 month ago
Activity icon

Started a new Conversation Digital Voucher Implementation For Restaurant Discounts

Hi everybody, this is more of an implementation question than a code one so sorry, I have been tasked to create a web app where people can buy discounted packs of meals online using Stripe as payment gateway, I got everything set up except dor the digital voucher, that is how users will notify the servers in the restaurant that they purchased a discounted meal, that the meal they are ordering was not "activated" before ans that it's a valid voucher, basically I have thought of three options but I'm not sure which one is the best:

1)Slide to unlock, the digital voucher has a "Slide to Unlock" at the bottom, the customer should slide to unlock when the server is present, once the customer slides the component whould change to grren color if voucher is valid and won't be able to use that voucher again. This one is my favorite right now.

  1. QR code, pretty simple, the digitla voucher is a r code the server can scan in order to activate and check the voucher is valid. This is ok, have to think more on the implementation tho

  2. Purchasable code, when you purchase a discount you get an unique, one-use code, you show or tell your code to the server and he "activates" it via an API call from the web app admin panel. I don't quite like this, too much hassle

I'm open to all kinds of ideas

Jul
24
1 month ago
Activity icon

Started a new Conversation How To Enable Strict Mode In Mobx Store, React-native.

Hi everybody, how can I enable strict mode for my mobx stores in my react-native map, I use mobx stores along with react context API and hooks. After reading docs strict mode makes it so I can only change observable state in actions.

/contexts/index.js

import React from 'react'
import { ThemeStore }  from '../stores/ThemeStore.js'
import { PostStore }  from '../stores/PostStore.js'

export const storesContext = React.createContext({
  postStore: new PostStore(),
  themeStore: new ThemeStore(),
})

/stores/PostStore.js


import { observable, computed, action, flow } from "mobx";
import axios from 'axios';

export class PostStore
{
    
    
    @observable postMessage = 'Nothing to see here';
    @observable post = {};
    @observable posts = [];
    @observable pagination = {};
    @observable postCount = 0;


    @computed get visiblePosts()
    {
        return this.posts.filter( post => post.isVisible);
    };


}
Jul
22
1 month ago
Activity icon

Started a new Conversation Avoid Relative Path Import Hell In React-native?

Hi everybody, I'm new to react-native coming from vue background, one thing I hate in react is having to use relative path imports in my components, I find myself doing something like:

import HomeScreen from '../../components/screens/HomeScreen'

I f my folder structure changes it means I will have to do a search and replace in all of m components using that component, not cool and prone to be a dev hell.

Is it possible to use absolute paths like with node modules, is there a library where I can use aliases or similar, with vue I could import my components in the app.js like Vue.component('home-screen ...) and I could use them without having to import, please help me out.

Jul
19
2 months ago
Activity icon

Started a new Conversation Help With Many To Many Realtionship

Hi everybody, I'm trying to make an app where airbnb hosts can have a log of their bookings, I created three models: Home, Guest and Booking. Booking being the main player, I also think there should be a pivot table but I'm not sure which models should it link... I decided to go with booking_guest but I'm getting the following error when I create a booking:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'booking_id' cannot be null (SQL: insert into `booking_guest` (`booking_id`, `guest_id`) values (?, 1), (?, 2))

I do something like this in my BookingController:

public function create(Request $request)
    {

        $guestIds = Guest::latest()->take(2)->pluck('id');
        $home = Home::findOrFail(1);

        $booking = new Booking();
        $booking->home_id = $home->id;
        $booking->guests()->attach($guestIds);
        $booking->save();
		
        return response()->json([
			'booking' => $booking,
        ]);
        
    }

I'm not feeling too sure about this configuration, could you guys share some light on me.

These are my models:


class Home extends Model
{
    
    public function guests()
    {
        return $this->belongsToMany('App\Models\Guest', 'guest_home', 'home_id', 'guest_id');
    }

    public function bookings()
    {
        return $this->hasMany('App\Models\Booking');
    }

}


class Booking extends Model
{
    
    public function guests()
    {
        return $this->belongsToMany('App\Models\Guest', 'booking_guest', 'booking_id', 'guest_id');
    }

}

class Guest extends Model
{
    
    public function bookings()
    {
        return $this->belongsToMany('App\Models\Booking', 'booking_guest', 'guest_id', 'booking_id');
    }

}

My migrations:

//Booking guest pivot table
Schema::create('booking_guest', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('booking_id')->index();
            $table->foreign('booking_id')->references('id')->on('bookings')->onDelete('cascade')->onUpdate('cascade');
            $table->unsignedInteger('guest_id')->nullable()->index();
            $table->foreign('guest_id')->references('id')->on('guests')->onDelete('cascade')->onUpdate('cascade');
            $table->timestamps();
        });

Schema::create('guests', function (Blueprint $table) {
            $table->increments('id');
            $table->string('fullName');
            $table->text('country');
            $table->timestamps();
        });

Schema::create('bookings', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('home_id')->index();
            $table->foreign('home_id')->references('id')->on('homes')->onDelete('cascade')->onUpdate('cascade');
            $table->timestamp('entryDate')->nullable();
            $table->timestamp('exitDate')->nullable();
            $table->timestamps();
        });

Schema::create('homes', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('host_id')->index();
            $table->foreign('host_id')->references('id')->on('hosts')->onDelete('cascade')->onUpdate('cascade');
            $table->string('fullAddress')->unique();
            $table->integer('rooms')->unique();
            $table->timestamps();
        });

Activity icon

Started a new Conversation Booking System Ala Airbnb Many To Many Relationship?

Hi everybody, I'm trying to create a system to log all bookings for a few airbnb hosts, at first I had two models Home and Guest, where a home can have many guests and a guest could book for many homes,

then I thought about creating a guest_home pivot table to link both tables... then things got complicated in my head, what about a Booking model, and (have that booking model act as a pivot table ?) , to me doing new Booking() seemed better than attaching ids to home model?

How could you guys go about this, it's making my brain malt right now...

I thought of doing something like this in my BookingController:

public function createBooking(Request $request)
    {

        $guestIds = Guest::latest()->take(3)->pluck('id');
        $home = Home::findOrFail($request->input('home_id', 2));

        $booking = new Booking();
        $booking->home_id = $home->id;
        $booking->guests()->attach($guestIds);
        $booking->save();
		
        return response()->json([
			'booking' => $booking,
        ]);
        
    }

Should I create home_guest pivot table, is a pivot table even needed? what models would I link, please bear with me, so far this is what I got:

Models

class Guest extends Model
{
    
    public function bookings()
    {
        return $this->belongsToMany('App\Models\Home', 'bookings', 'guest_id', 'home_id');
    }

}

class Home extends Model
{
    
    public function guests()
    {
        return $this->belongsToMany('App\Models\Guest', 'bookings', 'home_id', 'guest_id');
    }

    public function bookings()
    {
        return $this->hasMany('App\Models\Booking');
    }

}

class Booking extends Model
{
    //Is Booking needed or I could make a pivot table like home_guest called 'bookings' ?
    public function guests()
    {
        return $this->belongsToMany('App\Models\Guest', 'booking_guest', 'booking_id', 'guest_id');
    }

}

Migrations:

Schema::create('bookings', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('home_id')->index();
            $table->foreign('home_id')->references('id')->on('homes')->onDelete('cascade')->onUpdate('cascade');
            $table->unsignedInteger('guest_id')->nullable()->index();
            $table->foreign('guest_id')->references('id')->on('guests')->onDelete('cascade')->onUpdate('cascade');
            $table->timestamps();
        });

Schema::create('homes', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('host_id')->index();
            $table->foreign('host_id')->references('id')->on('hosts')->onDelete('cascade')->onUpdate('cascade');
            $table->string('fullAddress')->unique();
            $table->integer('rooms')->unique();
            $table->timestamps();
        });

Schema::create('guests', function (Blueprint $table) {
            $table->increments('id');
            $table->string('fullName')->unique();
            $table->string('identificationType')->unique();
            $table->text('country')->nullable();
            $table->timestamps();
        });
Jul
15
2 months ago
Activity icon

Started a new Conversation Class Or Function Components In React-native To Inject Mobx Store?

I'm new to react-native and trying to set up my app with mobx for state management, when trying to inject rootStore into my HomeScreen component I get the following error:

Error: C:\xampp\htdocs\second-try\screens\HomeScreen.js: Leading decorators must be attached to a class declaration

This is my component, as you see I'm suing function based component and I get a warning, but how can I use components ass Class and inject mobx stre into my react-native component.

My HomeScreen file:

import * as React from 'react';
import { StatusBar } from 'expo-status-bar';
import { View, Text, StyleSheet } from 'react-native';


@inject(stores => ({
  postStore: rootStore.postStore,
  //authStore: rootStore.authStore,
  })
)

//ERROR IS RIGHT
@observer
const HomeScreen = function()
{
  return (
    <View style={styles.container}>
      <Text>{postStore.postMessage}</Text>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default HomeScreen;

Jul
03
2 months ago
Activity icon

Replied to Fixed Div Scrollbar Under Browser Scrollbar Fix

The modal is overflowing however the isssue is I can't see the scrollbar of my modal... I see the body scrollbar instead. Z-index ain't helping...

Activity icon

Started a new Conversation Fixed Div Scrollbar Under Browser Scrollbar Fix

Hi everybody, in my web app I want to have a fixed div modal wich ocuupies the whole screen, however this modal's scrollbar is not visible, instead only the body scrollbar is visible, I assume my fixed dic scrollbar is right behind the body scrollbar, this makes it so I can only use arrow keys to navigate down while seeing the body scrollbar instead of fixed modla scrollbar...

.fixed_div{width:100vw; height:100vh; background-color:rgb(240,240,240); overflow-y:scroll !important; overflow-x:hidden; display:flex; flex-direction:column; position:fixed; top:0px; left:0px; bottom:0px; right:0px; z-index:99999999999999999999999999999999999999999999999999999999999999999999 !important;}

.body{margin:0px 0px 0px 0px; background-color:white; position:relative; display:flex; flex-direction:column; max-width:100%; min-height:100%; height:auto; overflow-x:hidden;}
Jun
30
2 months ago
Activity icon

Started a new Conversation Horizontall Scroll In Flex Container

Hi everybody, I want to have horizontal scrolling inside my container of flex items, sadly I can't seem to get it to work and items are shrinking instead of enabling horizontal scrolling inside the wrapper. This is my code:

<div style="width:100%; height:400px; display:flex; position:relative;">
            <div v-border class="" style="width:auto; height:100%; display:flex; overflow-x:scroll !important;">
                <div style="width:30vw; height:100%; background-color:red; margin:0px 20px 0px 0px;  flex:1;"></div>
                <div style="width:30vw; height:100%; background-color:red; margin:0px 20px 0px 0px; flex:1;"></div>
                <div style="width:30vw; height:100%; background-color:red; margin:0px 20px 0px 0px; flex:1;"></div>
                <div style="width:30vw; height:100%; background-color:red; margin:0px 20px 0px 0px; flex:1;"></div>
                <div style="width:30vw; height:100%; background-color:red; margin:0px 20px 0px 0px; flex:1;"></div>
                <div style="width:30vw; height:100%; background-color:red; margin:0px 20px 0px 0px; flex:1;"></div>
                <div style="width:30vw; height:100%; background-color:red; margin:0px 20px 0px 0px; flex:1;"></div>
                <div style="width:30vw; height:100%; background-color:red; margin:0px 20px 0px 0px; flex:1;"></div>
            </div>
        </div>
Jun
27
2 months ago
Activity icon

Started a new Conversation Marker Not Appearing On My Google Map In Laravel-Vue

Hi everybody, I'm using geolocationAPI to get my position and put a marker on the map, I get my position all right but the marker doesn't appear on the map, what would I be doing wrong? My code is pretty straightfordward and the initialLocation object is solething like this:

{ lat: 36.7202947, lng: -4.4064701 }

Which is a valid lat-lng object afaik.

My vue single component:

<template>
<div class="GOOGLEmap2_canvas" id="mapita"></div>
</template>
<!--SCRIPTS-->
<script>
export default {
name: 'GoogleMap5',


data() {
    return {
        map:null
        
    }
},


props:
{
    origin: { default: () => { return  { lat: 37.727312, lng: -4.424144 } } },
    zoom: { default:13, type:Number }
},


mounted()
{
    console.log(this.$options.name+' component successfully mounted');
    this.getInitialPosition()
},


methods: 
{


    getInitialPosition()
    {
        const self = this;
        var mapOptions = { zoom: this.zoom, center: this.origin };
        this.map = new google.maps.Map(document.getElementById('mapita'), mapOptions);

        navigator.geolocation.getCurrentPosition(function(position)
        {
            var initialLocation = { lat: position.coords.latitude, lng: position.coords.longitude };
            //var initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            self.map.setCenter(initialLocation);
            self.map.setZoom(self.zoom);

            var marker = new google.maps.Marker({ initialLocation, map: self.map }); 

        }, function(positionError)
        {
            console.log('user denied location prompt');
            self.setCenter(new google.maps.LatLng(self.origin.lat, self.origin.lng));
            self.map.setZoom(self.center);
        });
    }

    
}


};
</script>
<!--STYLES-->
<style scoped>
.GOOGLEmap2_canvas{width:100%; height:100%; background-color:rgb(235,235,235);}
</style>