Gabotronix

Gabotronix

Member Since 2 Years Ago

Experience Points
29,640
Total
Experience

360 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
29,640 XP
Oct
27
22 hours ago
Activity icon

Started a new Conversation Laravel: Nested Relationship WhereHas?

In my app I have venues, each venue can have discounts, each discount have codes to redeem.

In order to redeem discount codes I have to look for a discount code belonging to a discount and to a specific venue, I know this has to be done with whereHas but I can't wrap my head on how to make this?

This is what I have so far:

$code = $request['code'];
$venue_id = $request['venue_id'];
$discount_id = $request['discount_id'];

$codeExists= DiscountCode::where('unicode', $code])
            ->where('purchasedDate', '!=', null)
            ->with(['discount.venue', 'user'])
            ->first();

Anyone can help me?

Schemas for my models:

Schema::create('discountcodes', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('discount_id')->index();
            $table->foreign('discount_id')->references('id')->on('discounts')->onDelete('cascade')->onUpdate('cascade');
            $table->unsignedInteger('order_id')->index()->nullable();
            $table->foreign('order_id')->references('id')->on('orders')->nullable()->onDelete('cascade')->onUpdate('cascade');
            $table->unsignedInteger('user_id')->index()->nullable();
            $table->foreign('user_id')->references('id')->on('users')->nullable()->onDelete('cascade')->onUpdate('cascade');
            $table->string('unicode')->unique();
            $table->timestamp('purchasedDate')->nullable();
            $table->timestamp('usedDate')->nullable();
            $table->timestamp('expirationDate')->nullable();
            $table->timestamps();
        });

Schema::create('discounts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('discountcategory_id')->index()->default(1);;
            $table->foreign('discountcategory_id')->references('id')->on('discountcategories')->onDelete('cascade')->onUpdate('cascade');
            $table->unsignedInteger('venue_id')->index()->default(1);
            $table->foreign('venue_id')->references('id')->on('venues')->onDelete('cascade')->onUpdate('cascade')->default(1);
            $table->string('title')->unique();
            $table->timestamp('expireDate');
            $table->timestamps();
        });

Schema::create('venues', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('address_id')->index();
            $table->foreign('address_id')->references('id')->on('address')->onDelete('cascade')->onUpdate('cascade');
            $table->string('name');
            $table->string('image')->nullable();
            $table->timestamps();
        });
Oct
15
1 week ago
Activity icon

Started a new Conversation Execute Node App In The Background As Service (without Routes) With Pm2

Hi everybody, I'm starting to tinker with node.js server, I created a node application which keeps a database in sync, the function of this app/script is to run an async function in 5 minutes intervals, for this I'm using node-cron, so far I got it to work after I visit my express route / .

Issue is I don't want to have to visit a route to start/stop/whatever the cron job, I have read about pm2 and would like to be able to execute my application as background with it.

Ideally I'd start and stop the cron job from the command line, where can I find a tutorial on how to do this in an ubuntu server?

My app.js file looks like this:

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

    app.get('/', async (req, res) => 
    {
        const job = new CronJob('0 */5 * * * *', function()
        {

            try
            {
                const databaseService = new DatabaseService();
                databaseService.syncDB();
            }
            catch(err)
            {
                console.error(err);
            }
        });

        job.start();
            
        res.send('Hello world');
    });


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


How to handle cron job without visiting route/script running from console in the background
Oct
14
1 week ago
Activity icon

Started a new Conversation Issue Scraping Html Table With Goutte

Hi everybody, I'm trying to scrape an html table of cities by population, with Goutte in laravel, I want to return the html table as php array and then turn it into json and save it to disk.

For some reason when I crawl the table I get an array full of null values, this is my code:

public function crawlAustraliaHtmlTable(Request $request)
    {
        $html='';
        $client = new Client();
        $url = 'http://www.geoba.se/population.php?cc=AU&st=city_rank_country&asde=&page=1';
        $crawler = $client->request('GET', $url);
        //$crawler->addHTMLContent($html);
        
        $table = $crawler->filter('table')->filter('tr')->each(function ($tr, $i) {
            return $tr->filter('td')->each(function ($td, $i) {
                $td->filter('a')->each(function ($a, $i) {
                    return $a->attr('href');
                });
            });
        });
        
        //print_r($table);

        $json = json_encode($table);

        $filename = 'cities_in_australia.json';

        File::put(public_path('/uploads/'.$filename),$json);

        return response()->json([
            'json' => $json,
        ]);
    }

The result (notice all the nulls for some reason).

[[null],[null,null,null,null,null],[null,null,null,null,null],[null,null,null,null,null],[null,null,null,null,null],[null,null,null,null,null],[null,null,null,null,null],[null,null,null,null,null],[null,null,null,null,null],[null,null,null,null,null],[null,null,null,null,null],...]]

The html table structure is like this:

<table border=0 cellpadding=3 cellspacing=3 class="table table-condensed table-noline">

<tr style="font-size: 16px;">

<th class="bottom" valign=top width=50 align=left NOWRAP><b><a class=redglow style="color:#0000FF;" href="population.php?cc=AU&st=crcountry&asde=d&page=1" onClick="recordOutboundLink(this, 'Population - City - Australia', 'Sort By Rank'); return false;">Rank</a></b></td>
<th class="bottom" valign=top width=200 align=left NOWRAP><b><a class=redglow style="color:#0000FF;" href="population.php?cc=AU&st=city&asde=d&page=1" onClick="recordOutboundLink(this, 'Population - City - Australia', 'Sort By City'); return false;">City</a></b></td><th class="bottom" valign=top width=125 align=left><b><a class=redglow style="color:#0000FF;" href="population.php?cc=AU&st=state&asde=d&page=1" onClick="recordOutboundLink(this, 'Population - City - Australia', 'Sort By State'); return false;">State</a></b></td><th class="bottom" valign=top width=100 align=left><b>Country</b></td><th class="bottom" valign=top width=75 align=right NOWRAP><b><a class=redglow style="color:#0000FF;" href="population.php?cc=AU&st=pop&asde=d&page=1" onClick="recordOutboundLink(this, 'Population - City - Australia', 'Sort By Population'); return false;">Population</a></b></td>
<td></td>
</tr>

	<tr style="font-size:13px;" class="bb">
	<td valign=top><a name="1"></a>1.</td>
	<td valign=top><a class=redglow style="color:#0000FF;" href="/location.php?query=2158177&geoid=Y" onClick="recordOutboundLink(this, 'Population - City - Australia', 'Melbourne'); return false;">Melbourne</a></td>
	<td valign=top width=150><a class=redglow style="color:#0000FF;" href="population.php?sc=Victoria&state=Victoria" onClick="recordOutboundLink(this, 'Population - City - Australia', 'Victoria'); return false;">Victoria</a></td><td valign=top><a class=redglow style="color:#0000FF;" href="country.php?cc=AU&year=2020" onClick="recordOutboundLink(this, 'Population - City - Australia', 'Australia'); return false;">Australia</a></td>
	<td valign=top align=right>3,730,206</td>
	
	<tr style="font-size:13px;" class="bb">
Oct
11
2 weeks ago
Activity icon

Started a new Conversation Detect Unicode In String And Transform It To String Character?

Hi everybody, I got a string representing an email like this one:

info\u0040tartaytantas.es

where \u0040 is actually "@" character represented like that instead of "@", I was wndering if there is a way to parse a string, detect any non well-formatted unicode characters and change them to their good string representation?

Oct
10
2 weeks ago
Activity icon

Started a new Conversation Issue With Match() And Email Regex Expression

Hi everybody, I have a function where I get the html of a website, then use match along with a regex rule to get the emails in that page, however for some reason I'm getting back a line that matches the regex without the actual email plus all of the DOM appended..

So problems:

  1. My regex is not actually working, I dn't get the email part of mailto:xxxx

  2. For some reason the whole DOM is getting console logged when I do console.log(matches[0]);

const websiteEmailRegex = 'mailto:([^\?]*)';

let HTML = document.documentElement.outerHTML;

let matches = HTML.match(websiteEmailRegex);
if(matches)
{
    console.log('email', matches[0]);
}

This is what I get in console:

mailto:[email protected]"> [email protected]</a></p>
<p>No cogemos pedidos por mail.</p>


<p></p>
                </div><!-- .entry-content -->

                <footer class="entry-footer">
                                        </footer><!-- .entry-footer -->
        </div>
</article><!-- #post-## -->

                </main><!-- #main -->
        </div><!-- #primary -->

</div></div>
        <footer id="colophon" class="site-footer" role="contentinfo" itemscope="" itemtype="http://schema.org/WPFooter">

                <div class="container">

                            <div class="footer-t">
        <div class="row">
            <div class="three-cols">
                <div class="col">
                                    </div>
                <div class="col center">
                    <section class="widget widget_contact_form">
                                        </section>
                </div>
                <div class="col">
                                    </div>
            </div>
        </div>
    </div>
    <div class="site-info">
        <span>
        ©2020 <a href="http://tartaytantas.es/">Tartaytantas - Tartas y bizccochos a domicilio en Aravaca</a>.        </span>
        Bakes and Cakes | Desarrollado por        <a href="https://rarathemes.com/" rel="nofollow" target="_blank">
            Rara Theme        </a>
        Funciona gracias a <a href="https://wordpress.org/">WordPress.</a>

    </div><!-- .site-info -->

                </div>

        </footer><!-- #colophon -->
        <div class="overlay"></div>
        <a href="javascript:void(0);" class="btn-top"><span>Arriba</span></a>

        </div><!-- #acc-content -->
</div><!-- #page -->

<script type="text/javascript" src="https://secureservercdn.net/160.153.137.170/zm5.b57.myftpupload.com/wp-content/themes/bakes-and-cakes/js/owl.carousel.min.js
Oct
09
2 weeks ago
Activity icon

Started a new Conversation Improve Performance Of Multiple Row Insertions In Eloquent

Hi everybody, I have a controller API method where I insert many rows (around 4000 - 8000), before inserting a new row I also check if a venue with the same ame was added already in the zone sothat's another Elouent call, my issue is I usually get timeout errors becuase the row inserting takes too much, I use set_time_limit(0) but this seems too hacky.

I think the key is the validation check I do before inserting a new row.

 //Check if there is a venue with same name and in the same zone already added
             $alreadyAdded = Venue::where('name', $venue['name'])->whereHas('address', function ($query) use ($address){
                $query->where('provinceOrState' , $address['provinceOrState']);
            })->orWhere('venueId',$venue['venueId'])->first();

Is there a way I can improve the performance of this method ? This is my complete method call:

public function uploadIntoDatabase(Request $request)
    {
        set_time_limit(0);

        $count = 0;

        foreach($request->input('venuesToUpload') as $index => $venue)
        {

             //Check if there is a venue with same name and in the same zone already added
             $alreadyAdded = Venue::where('name', $venue['name'])->whereHas('address', function ($query) use ($address){
                $query->where('provinceOrState' , $address['provinceOrState']);
            })->orWhere('venueId',$venue['venueId'])->first();

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

               
            }
        }

        return response()->json([
            'message' => $count.' new venues uploaded to database',
        ]);
    }
Oct
01
3 weeks ago
Activity icon

Started a new Conversation Is This Kind Of Accesor Possible?

I have a Model called restaurants, a restaurant can have many discounts and each discount has an unique code, now each discount belongs to a category. I want to add an accesor to my Venue model called has_live_deals, in order to do that I'd have a method similar to this in my model:

public function getHasLiveDealsAttribute()
    {
        //This should return true or false depending on the value of count
        $count= Discount::whereHas('discountcodes', function ($query){
            $query->where('purchasedDate' , null);
        })->whereHas('discountcategory_id', function ($query){
            $query->where('id' , 1);
        })->count;
    }

The query would be something like that but I don't know how to implement it the right way, I should use $this (meaning the retrieved restaurant) but don't kow where or how, can you guys help me?

My objective is to add this getter to $appends array so this query would be done for each restaurant I grab from database, I'm afraid this would not be very performant, am I right or is it ok?

Activity icon

Started a new Conversation Filter Array By Multiple Categories

Hi everybody, I hve an array of venues, each venue can have discounts of multiple categories, a user can choose to filter venues by the category of their discounts (user can choose multiple categories too!), how can I filter only the venues who have discounts of the chosen categories.


let selectedCategories = [1,3];

let venues =
[
    { name:'Venue 1', discountsOfCategoryOneCount:2, discountsOfCategoryTwoCount:4 },
    { name:'Venue 2', discountsOfCategoryOneCount:1, discountsOfCategoryTwoCount:8 },
    { name:'Venue 3', discountsOfCategoryOneCount:4, discountsOfCategoryTwoCount:3 }
];

let filteredResults = venues.filter((item) => /*HOW TO DO THIS*/);
Sep
29
4 weeks ago
Activity icon

Started a new Conversation Examples Of React Native Authentication Using Laravel Passport

Hi everybody, I can't seem to finc complete examples of using Laravel Passport for user authentication (email and password), do you guys have a working example of the set up?

Sep
28
4 weeks ago
Activity icon

Started a new Conversation React Native: Is Tit Possible To "snap" A FlatList Scroll Items

I want to use a FlatList component as a Picker, in order to give it that feel I want the vertical items to "snap" each one, this is not like yur typical scrolling behaviour, I don't know how to explain better and I'm not sure this is possible at all but I'd like to hear from other seasoned developers.

<FlatList decelerationRate={"fast"} data={modalPickerStore.pickerData} keyExtractor = { (item, index) => item.title+index.toString() } renderItem={({ item }) => 
                <TouchableHighlight onPress={ ()=>{ modalPickerStore.setSelectedPickerData(item.value) } } style={{ width:'100%', height:50, flexDirection:'column', alignItems:'center', justifyContent:'space-between;' }}>
                    <Icon name={item.icon} size={30} color="black"/>
                    <Text style={{ color:'rgb(255,52,89)', textAlign:'center' , fontSize:16, fontWeight:'bold' }}>{ item.title }</Text>
                    <Text style={{ color:'rgb(255,52,89)', textAlign:'center' , fontSize:16, fontWeight:'bold' }}>Hecho</Text>
                </TouchableHighlight>}
                />
Sep
27
1 month ago
Activity icon

Started a new Conversation Laravel User Authentication In React-native?

Hi everybody, I'm working on my first react-native app, coming from vue-laravel background I was wondering if it's actually possible to use laravel normal auth for my react-native, so far it seems I can succesfully login a user sending their credentials via POST request to my API, however subsequent uses of Auth helper fail, that is I can't get the logged user using Auth::user(), it returns null...

Is this possible to accomplish? I have read about firebase auth but I don't feel like adding another database system to my laravel main Mysql database, truth is I don't know for sure what laravel uses for authentication under the hood so I can't get this to work.

Any help would be appreciated.

Activity icon

Started a new Conversation React-Native: Issue Persisting Data In Mobx Store

Hi everybody, I'm working on my first react-native app and I decided to use mobx for state management, I also want to persist some pieces of data so I installed mobx-persit module, I'm trying to get mobx persist to work with the multi store setup I have but I'm getting the following error:

[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: 'Reaction[[email protected]]', [Error: [serializr] Failed to find default schema for null]

My UserStore is pretty simple so far:


import { observable, action } from "mobx";
import { persist } from 'mobx-persist'

export class UserStore
{
    
    
    @persist @observable user = {};
    @persist @observable users = [];


    @action.bound setUser(payload)
    {
        this.user = payload;
    }

    @action.bound setUsers(payload)
    {
        this.users = payload;
    }


}

First my store setup uses multiple stores along with react Context API along with a useStores hook, this way I can inject my stores into my components pretty easily:

/contexts/index.js

import React from 'react'
import { configure } from 'mobx';
import { create } from 'mobx-persist'
import { UserStore }  from '../stores/UserStore.js'


const hydrate = create({
    storage: AsyncStorage,
    jsonify: true
})

export const storesContext = React.createContext({
    userStore: new UsertStore(),
});


hydrate('userStore', storesContext.userStore).then(() => console.log('UserStore has been hydrated'));


configure({ enforceActions: "observed" });

Than my use-store hook

//hooks/use-stores.js

import React from 'react'
import { storesContext } from '../contexts/index.js'

export const useStores = () => React.useContext(storesContext);

then in my functional components I can do something like this:

import { useStores } from '@hooks/use-stores'
const { userStore } = useStores();
Activity icon

Started a new Conversation React-Native Expo Debug Errors Not Showing Any Useful Info Or Error Message

I'm a react-native newbie and I'm using expo to build my maps, one issue I have is when I communicate with my backend (localhost) via axios and something goes wrong in the backend I get a pretty generic error message, only useful thing here is the status error code 500.

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

Take a look, even though I'm wrapping async/await in try/catch block I get no error message or error line, this makes debugging a hell, is developing with expo/react always like this?

Sep
25
1 month ago
Activity icon

Started a new Conversation React Native: Access Mobx Store Action/variable Inside Another Store

Hi everybody, I'm a react-native newbie, I'm using mobx for state management, I set up my app to use context API and hooks to utilize stores in my components easily, I got this implementation from mobx-react native docs.

  1. Issue is I want to invoke an action and use observables from themeStore inside my postStore, how can I do that, is that even possible? in the past with vuex I was able to do it pretty easily.

  2. Is this mobx + context + hooks implementation good?

First I set up context:

//contexts/index.js

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

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

configure({ enforceActions: "observed" });

Then I created use-stores hook which I import into the components I want to invoke store actions and variables from:

//hooks/use-stores.js

import React from 'react'
import { storesContext } from '../contexts/index.js'

export const useStores = () => React.useContext(storesContext);

That way in my app I can do:

import { useStores } from '@hooks/use-stores'

const { postStore, themeStore } = useStores();

My stores are normal mobx stores, they contain observables, actions and flow actions for async/await operations.


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

export class PostStore
{
    @observable postCount = 0;

    @action.bound increasePostCount()
    {
        this.postCount++;
    }
}

Sep
24
1 month ago
Activity icon

Started a new Conversation React: Apply Multiple Filters To Array

Hi everybody, I'm starting with react and I have an array of objects called arrayToFilter I want to apply multiple filters to, ideally when a user changes the filter select options all filters should be applied to the array and the results returned into a filteredResults array to show, I already have each filter function and their constants but I don't know how to apply all the filters one after another...

Here is my code:

    const [ arrayToFilter, setArrayToFilter ] = useState([ /*array of objects to apply filters to*/ ]);
    const [ filteredResults, setFilteredResults] = useState([ /*array of filtered objects*/ ]);
    const [ categoryOptions, setCategoryOptions ] = useState([ 1,2,3 ]);
    const [ selectedCategoryOptions, setSelectedCategoryOptions ] = useState([ ]);
    const [ searchName, setSearchName ] = useState('');
    const [ hideVenuesWithoutDiscounts, setHideVenuesWithoutDiscounts ] = useState(true);

    const filterHideVenuesWithoutDiscounts = () => 
    {
        if(hideVenuesWithoutDiscounts)
        {
            return arrayToFilter.filter(item => item.discounts.length > 0);
        }
        else
        {
            return arrayToFilter;
        }   
    };

    const filterSelectedCategoryOptions = () => 
    {
        return arrayToFilter.filter(item => item.category_id.includes(selectedCategoryOptions));
    };

    const filtersearchName = () => 
    {
        return arrayToFilter.filter(item =>  item.name.toLowerCase().indexOf(searchTerm.toLowerCase()) != -1);
    };

    useEffect(() => 
    {
        //Filter options updated so apply all filters here
    },
    [searchName, hideVenuesWithoutDiscounts, selectedCategoryOptions]);

Notice useEffect, afaik this is like watch property in vue, I'd like to fire all the filters when a filter input changes

Sep
23
1 month ago
Activity icon

Started a new Conversation SQL Harvesine Law To Grab Nearest Coordinates Question

in my app I want to show nearest places from map center coordinate, after looking for solutions I found a raw SQL query I could use in my laravel app:

This is my method:

$venues = Venue::select(DB::raw('*, ( 6367 * acos( cos( radians('.$latitude.') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('.$longitude.') ) + sin( radians('.$latitude.') ) * sin( radians( lat ) ) ) ) AS distance'))
    ->having('distance', '<', 25)
    ->orderBy('distance')
    ->get();

It is working perfectly but right here:

->having('distance', '<', 25)

I don't know what kind of measurement the 25 is, is it kilometers, miles, obviously it's not meters, anybody can help me?

Sep
20
1 month ago
Activity icon

Started a new Conversation Puppeteer.js Inside Loop Performance Question, Reusing Browser Instances?

Hi everybody, I'm making a scraping app, I have an array of urls from a single domain with headless puppeteer.js.

For each url I have I launch a browser, check if I'm logged, if not, log and write cookies for next iteration of the loop (this is soI don't have to login each time).

After that I do some classic scraping, close the page and close the browser, back to the next iteration of the loop and the same again.

I was wondering if it would be possible to increase the performance and overall quality of my operations, I think opening and closing chrome instance in loop is pretty CPU intensive, I don't want memory leaks either, can I alter my code to reuse browser or page intances for my script.

async scrapeForResults()
    {
        let urls = [ ... ]:

        for(var i = 0; i < urls.length; i++)
        {
            let response = await this.scrapWebForData(urls[i]);
            console.log('Contact info scraped - - - - - - - -');
            
        }
    }

puppeteer.js action, I do this for each url of my array, all urls are from the same domain:

async scrapWebForData(url)
    {
        
        let browser = await puppeteer.launch({ headless: true});

        const context = browser.defaultBrowserContext();
        context.overridePermissions("https://www.facebook.com", []);
        let page = await browser.newPage();
        await page.setDefaultNavigationTimeout(100000);
        await page.setViewport({ width: 1365, height: 623 });
        
        if (!Object.keys(cookies).length)
        {
            this.handleLoginCookies(page);
            let currentCookies = await page.cookies();
            fs.writeFileSync('./cookies.json', JSON.stringify(currentCookies));
        }
        else
        {
            await page.setCookie(...cookies);
            await page.goto(facebook, { waitUntil: "networkidle2" });
            //DO ACTION HERE
            
        }
        
        await page.close();
        await browser.close(); 
    }
Sep
19
1 month 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 month 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
1 month 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
1 month 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
1 month 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 month 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 month 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 month 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
2 months 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
2 months 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
2 months 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
2 months 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
2 months 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?