Gabotronix

Member Since 3 Years Ago

Experience Points
31,700
Total
Experience

3,300 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.

  • Community Pillar

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

Level 7
31,700 XP
Feb
26
2 months ago
Activity icon

Started a new Conversation Custom .bat File, Opening Multiple Tabs And Executing A Command In Each One

sorry for rookie custom but I want to make my dev experience easier, so I want to create custom command .bat file in order to open multiple tabs and executing a command in each one (For.example php artisan serve, npm run watch...).

What I tried:

C:\Users\GABRIEL\Desktop\custom-command.bat

I created .bat file like this:

cmd.exe && cd C:\xampp\htdocs\kinshiki && php artisan serve

cmd.exe && cd C:\xampp\htdocs\kinshiki&& npm run watch

cmd.exe && cd C:\xampp\htdocs\ishhiki && expo start

But when I execute file I get an error:

"C:\Users\GABRIEL\Desktop\custom-command.bat" command is not recognized as an internal or external
Jan
25
3 months ago
Activity icon

Started a new Conversation React Native: Issue When Rendering With Map And Index

Hi everybody, I have a multi-step form and in the top header I want to show some kind if breadcumbs, I'm trying to make it so between each breadcumb there's a line but currently I can only show a line for the last case in my condition (in this case, between 3 and 4, when it should look something like:

1 - 2 - 3- 4

while currently I have:

1 2 3 - 4

Have a look at my image to know what I'm talking about:

https://i.imgur.com/EUqL9Q4.jpg

My code is as follows:

const [ steps, setSteps ] = useState([ { title:'Detalles' }, { title:'Horario' }, { title:'Fotos' }, { title:'Menu' } ]);

<View style={{ width:'100%', backgroundColor:'white',flexDirection:'row', alignItems:'center', justifyContent:'space-around', position:'relative' }}>
        {steps.map((step,index) => {return (
            <>
            <View style={{ flexDirection:'column',alignItems:'center',justifyContent:'center' }}>
            <TouchableOpacity onPress={ ()=>{ onStepPressed(index+1) } } style={{ width:30,height:30,borderRadius:30/2, ...venueStore.currentStep == index+1 ? { backgroundColor:'rgb(3,91,150)' } : { backgroundColor:'rgb(150,150,150)' }, alignItems:'center',justifyContent:'center' }}>
                <Text style={{ fontSize:14, color:'white' }}>{index+1}</Text>
            </TouchableOpacity>
            {/*<Text style={{ fontSize:14, color:'rgb(68,68,68)' }}>{step.title}</Text>*/}
            </View>
            { index == 0 || index == 1 || index == 2 && (<View style={{ width:45,height:2,backgroundColor:'rgb(68,68,68)' }}></View>)}
            </>
        )})}
        </View>

Any idea how I can achieve my desired result

Jan
22
3 months ago
Activity icon

Started a new Conversation Composer: Your Requirements Could Not Be Resolved To An Installable Set Of Packages.

Hi everybody, in my laravel app I want to enable fcm with laravel-notification-channels /fcm, this package now uses kreait/laravel-firebase for firebase credentials setup.

First I installed laravel notifications package without issues, with this command:

composer require laravel-notification-channels/fcm:~2.0

Now, when I try to install laravel-firebase with the following command:

composer require kreait/laravel-firebase

I get the following composer warning in my commadn prompt:

Warning from https://repo.packagist.org: You are using an outdated version of Composer. Composer 2.0 is now available and you should upgrade. See https://getcomposer.org/2
Using version ^3.0 for kreait/laravel-firebase
./composer.json has been updated
Loading composer repositories with package information
Warning from https://repo.packagist.org: You are using an outdated version of Composer. Composer 2.0 is now available and you should upgrade. See https://getcomposer.org/2
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravel-notification-channels/fcm 2.1.1 requires kreait/laravel-firebase ^1.3 || ^2.1 -> satisfiable by kreait/laravel-firebase[1.3.0, 1.4.0, 1.5.0, 2.1.0, 2.2.0, 2.3.0, 2.3.1, 2.4.0] but these conflict with your requirements or minimum-stability.
    - laravel-notification-channels/fcm 2.1.1 requires kreait/laravel-firebase ^1.3 || ^2.1 -> satisfiable by kreait/laravel-firebase[1.3.0, 1.4.0, 1.5.0, 2.1.0, 2.2.0, 2.3.0, 2.3.1, 2.4.0] but these conflict with your requirements or minimum-stability.
    - laravel-notification-channels/fcm 2.1.1 requires kreait/laravel-firebase ^1.3 || ^2.1 -> satisfiable by kreait/laravel-firebase[1.3.0, 1.4.0, 1.5.0, 2.1.0, 2.2.0, 2.3.0, 2.3.1, 2.4.0] but these conflict with your requirements or minimum-stability.
    - Installation request for laravel-notification-channels/fcm (locked at 2.1.1, required as ~2.0) -> satisfiable by laravel-notification-channels/fcm[2.1.1].


Installation failed, reverting ./composer.json to its original content.

How can I fix this?

Jan
21
3 months ago
Activity icon

Started a new Conversation SafeAreaView Top Not Showing Background Color In React-native

Hi everybody, I have a react native app where I want to show the top part of device with brand color (blue in this case) but instead it shows transparent/grey and only the main body shows blue color, how can I make it so it also shows top colored blue instead of grey?

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

in my App.js

return (
    <SafeAreaView style={{ flex: 1, backgroundColor: 'rgb(3,91,150)', paddingTop: Platform.OS === 'android' ? 0 : 0 }}>
        <NavigationContainer>
            <ROOTSTACK1></ROOTSTACK1>
        </NavigationContainer>
    </SafeAreaView>
    );

How can I make it so the top part is colored instead of grey color in image.

Activity icon

Started a new Conversation LogBox Ignore Warnings Not Working In React Native?

Hi everybody, I have an app made with react-native CLI, my version of RN is 0.63, I'm getting annoying moment.js warning like bellow:

Require cycle: node_modules\moment\src\lib\create\local.js -> node_modules\moment\src\lib\create\from-anything.js -> node_modules\moment\src\lib\create\from-string-and-array.js -> node_modules\moment\src\lib\create\from-string-and-format.js -> node_modules\moment\src\lib\create\from-array.js -> node_modules\moment\src\lib\create\local.js

I'm trying to make it so it will ignore this warning by using LogBox but it's not working.

I'm doing this in my App.js file:

import { LogBox  } from 'react-native';
LogBox.ignoreLogs(['Require cycle:']);

Any idea how can I make it so react-native will ignore the warnings?

Activity icon

Started a new Conversation React Native. Undefined Is Not An Object (evaluating '_this.props.updateCellsBatchingPeriod')

Hi everybody, I have a react-native app created with RN CLI, using react-native 0.63, I'm trying to use SectionList but I'm getting the following error:

undefined is not an object (evaluating '_this.props.updateCellsBatchingPeriod')

Full error:

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

My code is pretty simple and the trace obviously points to SectionList being the problem.

return (
    <View style={{ flex:1, backgroundColor:'white' }}>
        <SectionList style={{ flex:1,backgroundColor:'rgb(235,235,235)' }} showsVerticalScrollIndicator={false} 
        sections={[{ title: 'Title', data: [ { id:1 },{ id:2 } ]}]}
        />
    </View>
    );

I remember this code working perfectly in my old expo app but now the same code fails

I found this in github but I'm not using Typescript so ...

https://github.com/facebook/react-native/issues/29437

Jan
18
3 months ago
Activity icon

Started a new Conversation Cannot Make Any Network Request (fetch) In React-native 0.63.4 (Android)

Hi everybody, I just started developing with react native for the first time, it's a simple android app I created with react-native init command (not using expo this time).

I'm trying to make a simple network request but for some reason it's not firing at all, if I check the network tab in chrome devtools react-native debugger I can clearly see no network request is firing at all, I tried with axios instead of fetch and still nothing. I run the app in my plugged android device with npx react-native run-android command.

I added INTERNET permissions to AndroidManifest.xml file too.

<uses-permission android:name="android.permission.INTERNET" />

In my App.js I have:

useEffect(() => 
    {
        console.log('App mounted');
        tryAsyncFetch();
    }, []);

const tryAsyncFetch = async () => 
    {
        try
        {
            console.log('Fetching from placeholder...');
            fetch('https://jsonplaceholder.typicode.com/todos/1')
            .then((response) => console.log('response',response.json())); 
        }
        catch (e) 
        {
            console.error(e);
        }    
    };

As you can see it's pretty simple but it's not working, if I check the network tab no XHR requests at all, no error in catch segment, nothing...

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

I can see the logs before the fetch (Fetching from placeholder...) but no console logged results, this is SO WEIRD...

When I used expo I remember fetch/android working perfectly

Jan
17
3 months ago
Activity icon

Started a new Conversation React Native: Suddenly No Fast Refreshing And No Console Logs...

Hi everybody, I'm relatively new to react native dev, suddenly I noticed my console logs are no longer showing and any code edits I do in VSCode are not automatically refreshed, I'm certain I enabled Fast Reload, and my console logs where appearing in the node command tab but they no longer do...

I use this command to test app in my plugged android device:

npx react-native run-android

This command opens jetifier and builds my app, also opens a node tab where my logs used to show but not any longer.

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

Jan
12
3 months ago
Activity icon

Started a new Conversation React Native: Animate (slide Down/up) View With Dynamic Height

Hi everybody, I'm trying to animate (slide down/up) a view containing a dynamic list, since that list is dynamic I don't know how to have an Animated.View with dynamic height, currently I use a fixed value in my code, which is very hacky. I'm a react-native rookie and react native animations seem QUITE complicated (I have been reading docs and wow) so any help is really appreacited.

//Currently using a fixed value (300), how to get height of dynamic height View container?
const [ bounceValue, setBounceValue ] = useState(new Animated.Value(300));

//Is the animated view hidden or not?
const [ isHidden, setIsHidden ] = useState(true);

//I toggle the animated slide with this method
const toggleSlide = ()=> 
    {    

    var toValue = 475; //How to get dynamic height of View to animate

    if(isHidden)
    {
        //Here I hide (slide down) the animated View container
        toValue = 0;
    }

    Animated.spring(
      bounceValue,
      {
        toValue: toValue,
        velocity: 3,
        tension: 2,
        friction: 8,
        useNativeDriver: true
      }
    ).start();

    setIsHidden(!isHidden);
    }

And in my view:

<Animated.View style={[styles.subView, {transform: [{translateY: bounceValue}]}, { padding:10,position:'absolute',backgroundColor:'white' }]}>
      
        {cartProducts).map((products,index) => {return (
                <View style={{ width:'100%',flexDirection:'row', alignItems:'center', justifyContent:'space-between',marginBottom:5}}>
                        <Text style={{ fontSize:14, color:'rgb(68,68,68)' }}>Product: {index+1}</Text>
                </View>)})}
        </View>
        </Animated.View>

Thanks in advance!

Jan
09
4 months ago
Activity icon

Started a new Conversation Find: Missing Argument To -exec

I'm trying to execute a bunch of commands in my ubuntu VPS:

sudo find /var/www/lacasadelmuelle.es -type d -exec chmod 755 && sudo find /var/www/lacasadelmuelle.es -type f -exec chmod 644 && sudo chmod 775 /var/www/lacasadelmuelle.es/public/uploads && sudo setfacl -Rdm u:www-data:rwx,u:GabotronES:rwx storage bootstrap/cache && sudo setfacl -Rm u:www-data:rwx,u:GabotronES:rwx storage bootstrap/cache

but for some reason I'm getting this error:

find: missing argument to `-exec'

What am I doing wrong??

Jan
06
4 months ago
Activity icon

Replied to Openweather.com API 5 Next Days Forecast Issue

Yeah but that endpoint is a paid service, is there really no way to get the data I want with my current free endpoint?

Jan
05
4 months ago
Activity icon

Started a new Conversation Openweather.com API 5 Next Days Forecast Issue

Hi everybody, this is my first time using openweather.com API for weather forecasts, I just want to show the following information for the next 5 days:

Min and Max temperature of each day Weather icon Current weather description (Drizzle, Sunny...)

Plain simple, for some reason I'm getting pretty weird results, take a look at the image bellow so you can understand (I THINK that this five results are actually of the same day, different timestamps, look at min/max temp, maybe? instead of the next 5 days...

https://i.imgur.com/QnWR4R5.jpg

This is my code:

async getForecast()
    {
        let url = "https://api.openweathermap.org/data/2.5/forecast";
        let payload = 
        {
            lat: this.$app.globals.origin.lat,
            lon: this.$app.globals.origin.lng,
            units: 'metric',
            APPID: '0feb06072d87320932559f321ca221fb',
            lang:'es',
            cnt:5
        };

        let response = await axios.get(url, { params: payload });
        this.data = response.data.list;
    }

In my view (Vue.js):

<div style="width:auto; height:100%; display:flex; align-items:center;">
                <a  style="width:auto; padding:10; height:100%; display:flex; flex-direction:column; align-items:center; justify-content:space-around;" v-for="(item,index) in data" :key="index">
                    <span class="fs_smaller c_normal">{{ item.main.temp_min }} / {{ item.main.temp_max }}</span>
                    <span class="fs_smaller c_normal">{{ item.weather[0].description }}</span>
                    <img style="width:50px; height:auto;" :src="'https://openweathermap.org/img/w/'+item.weather[0].icon+'.png'">
                </a>
            </div>
Jan
02
4 months ago
Activity icon

Started a new Conversation React Native Remote Push Notifications From Laravel

Hi everybody, I want to implement remote push notifications into my react-native frontend, for example when a new deal is available for users nearby I want to send a notification to these users from my laravel backend.

What's a scalable and future-proof way to handle this, preferably a free service.

Dec
31
4 months ago
Activity icon

Started a new Conversation React-Native:State Changes Affecting View Only On Next Action?

Hi everybody, I have a component where user can add items to their shopping cart, next to each item it shows either a plus icon (add) or the number of items of that type in the shopping cart (chosenProducts state variable), adding items works well but for some reason the item count only updates after the next item is added instead of inmediately "reacting" to an added item...

Summary: item count UI doesn't update after item is added, updates after the next item is added (whatever item that is.

const [ chosenProducts, setChosenProducts ] = useState([]);
const [ chosenProductIds, setChosenProductIds ] = useState([]);
const [ data, setData ] = useState([ {id:1}, {id:2}, {id:3}, {id:4}, {id:5}, {id:6} ]);

const showProductCount = (item) =>
    {
        let finds = _.filter(chosenProductIds, id => id == item.id);
        if(finds.length > 0)
        {
            return (<Text style={{ fontSize:16,color:'white' }}>{finds.length}</Text>);
        }
        else
        {
            return (<MaterialCommunityIcon name="plus" style={{ color:'white', fontSize:22 }}/>)
        }
    };

const addItem = (product) =>
    {
        var copy = [...chosenProducts];
        copy.push(product);
        var chosenProductId = _.map(chosenProducts, product => product.id);
        setChosenProducts(copy);
        setChosenProductIds(chosenProductId);
    }


<FlatList showsVerticallScrollIndicator={false} style={{ flex:1}} vertical={true} data={data} keyExtractor={item => item.id.toString()}
       renderItem={({ item, index }) => 
       (<TouchableOpacity onPress={ ()=>{ addItem(item) } } style={{ width:'15%',flexDirection:'column',alignItems:'center'}}>
       <View style={{  width:35,height:35,borderRadius:5,backgroundColor:'rgb(3,91,150)',flexDirection:'column',alignItems:'center',justifyContent:'center' }}>
           {showProductCount(item)}
       </View>
   </TouchableOpacity>)
       
        }
    />

Is it beacuse I'm using a function to return JSX instead of conditional rendering inside JSX itself?

Dec
30
4 months ago
Activity icon

Started a new Conversation React Native: Cannot Use Function As Default State Hook?

Hi everybody, I have a function that takes a few discounts and groups them by days, so the final result is an array of 7 representing each day with a few discounts or none in each index, for some reason this computation makes the UI don't feel very snappy, only fully completing when I press the UI and showing an uncompleted result UI before that...

I tried placing a function which gives me the resulting array to the default state of my state hook but I gwt the following error:

getVenueDiscounts is not a function

Before this I was using useEffect with empty array to get my array but as I said it didn't feel very snappy...

Here is my method, maybe the problem is I have not optimized my business logic, is it possible to do this calculations better , maybe with a lodash method?

My method for grouping discounts by week days:

const [ weekDiscounts, setWeekDiscounts ] = useState(getVenueDiscounts());

const getVenueDiscounts = () =>
    {
        if(discounts.length == 0)
        {
        var weekDiscountsCopy = [ [], [], [], [], [], [], [] ];
        
        //let weekDiscountsCopy = [...weekDiscounts];
        //let response = await venueStore.getVenueDiscounts({ id:1 });
        console.log(response.data);
        let allDiscounts = _.cloneDeep(venueStore.myDiscounts);
        //let allDiscounts = response.data.discounts;
        //Alert.alert(response.data.discounts.length+' discounts');
        //setDiscounts(discounts);
        console.log(response.data.discounts[0].days);
        for(var i=0; i<response.data.discounts.length;i++)
        {
            let discountDays = allDiscounts[i].days;
            for(var x=0; x<discountDays.length;x++)
            {
                if(discountDays[x].id == 1) 
                {
                    weekDiscountsCopy[0].push(allDiscounts[i]);
                }
                else if(discountDays[x].id == 2) 
                {
                    weekDiscountsCopy[1].push(allDiscounts[i]);
                }
                else if(discountDays[x].id == 3) 
                {
                    weekDiscountsCopy[2].push(allDiscounts[i]);
                }
                else if(discountDays[x].id == 4) 
                {
                    weekDiscountsCopy[3].push(allDiscounts[i]);
                }
                else if(discountDays[x].id == 5) 
                {
                    weekDiscountsCopy[4].push(allDiscounts[i]);
                }
                else if(discountDays[x].id == 6) 
                {
                    weekDiscountsCopy[5].push(allDiscounts[i]);
                }
                else if(discountDays[x].id == 7)
                {
                    weekDiscountsCopy[6].push(allDiscounts[i]);
                }
            }
            //setWeekDiscounts(weekDiscountsCopy);
            setDiscounts(allDiscounts);
            return weekDiscountsCopy;
        }
    }
    };

Thanks in advance!

Dec
29
4 months ago
Activity icon

Started a new Conversation Two Colored Circle In React Native? Two Semi-circles

Hi everybody, is it possible to create a two colored circle in react-native without svg? I made a quick mockup in paint.net so you can see what I exactly want.

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

Thanks in advance

Activity icon

Started a new Conversation Compare Datetime String With Carbon Instance

Hi everybody, in my Order model I have a field called "pickUpDate' of type string that represents a datetime of type "D-M-YYYY", like in Europe.

Now I want to check if this date/string is after today's date, I was wondering if I have to do some Carbon parsing (and how?) of the string field or Eloquent will be able to do it on its own.

This is my method:

$orders = Order::whereHas('venue', function($q2) { 
            $q2->where('id', 1); })
        ->where('pickUpDate','>',$today)
        ->whereYear('created_at', Carbon::now()->format('YYYY'))
        ->with(['venue', 'discounts', 'products'])->latest()->get();

Casting or changing the field type to timestamp is not a possibility, thanks in advance!

Dec
24
4 months ago
Activity icon

Started a new Conversation React Native: Trying To Pass A Reference Function Via Props

Hi everybody, I created a reusable FlatList component which implements pagination, I'm trying to pass via props a function which makes an axios call and retrieves data from backend to populate the FlatList, however I'm getting the following error:

TypeError: [endAction] is not a function

Also this one:

TypeError: [store][action] is not a function

This is how I pass props to my custom component:

<RList1 store='venueStore' action='getVenueReviews' endAction={venueStore.getVenueReviews} data={[]} renderItem={itemView}></RList1>

And this is how I call the function (two ways, both give me same TypeError...):

let response = [store][action]({ params : params });
let response = [endAction]({ params : params });

My full custom component, just in case:

export default RList1 = observer((props) => 
{
    
    const [ data, setData ] = useState([]);
    const [ loader, setLoader ] = useState(0);
    const [ page, setPage ] = useState(1);
    const [ paginate, setPaginate ] = useState(2);
    const [ pagination, setPagination ] = useState(null);
    const [ numberOfPages, setNumberOfPages ] = useState(10);

    const { id=1,store,action,endAction, ...rest } = props;

    useEffect(() => {
        console.log('RList1 mounted');
        onEndReached();
    }, []);

    const onEndReached = async () =>
    {
        if(page < numberOfPages)
        {
            setLoader(0);
            try 
            {
                setLoader(1);
                console.log('fetching data');
                let params = { id:id, page : page, paginate : paginate };
                let response = [store][action]({ params : params });
                //let response = [endAction]({ params : params });
                setData([...data, ...response.data.data.data]);
                setPagination(response.data.pagination);
                setNumberOfPages(response.data.pagination.last_page);
                setLoader(2);
            } 
            catch (error)
            {
                setLoader(3);
                throw error;
            }
        }
    };
    
    return(
    <View style={{ flex:1 }}>
        <FlatList  style={{ flex:1,backgroundColor:'rgb(235,235,235)'}}  data={data} keyExtractor={item => item.id.toString()} extraData={loader}
        onEndReached={ ()=>{ onEndReached() } } onEndReachedThreshold={0.1}
        {...rest}
        />
    </View>
    );
        

});
Dec
23
4 months ago
Activity icon

Started a new Conversation Can't Select Specific Relationship Columns With Eloquent's With Method

Hi everybody, I want to improve the resolution times of my backend axios calls and so I'm trying to use with method special syntax for selecting specific columns, but for some reason category field is returning null.

In my method:

$venues = Venue::select(['id','name','lat','lng'])->with('category:id,title')->take(10)->get();

My venue relationship:

public function category()
    {
        return $this->belongsTo('App\Models\VenueCategory', 'venuecategory_id');
    }

and VenueCategory

public function venue()
    {
        return $this->belongsTo('App\Models\Venue', 'venue_id');
    }

The resulting venue payload is like this (notice category is null)

Object { id: 1, name: "El Pimpi", lat: "36.7219260", lng: "-4.8594939", category: null}

Venue migration:

Schema::create('venues', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('venuecategory_id')->index();
            $table->foreign('venuecategory_id')->references('id')->on('venuecategories')->onDelete('cascade')->onUpdate('cascade');
            $table->unsignedInteger('user_id')->index()->nullable();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->string('name');
            $table->string('description');
            $table->string('image')->nullable();
            $table->string('address')->nullable();
            $table->text('openingTimes')->nullable();
            $table->decimal('lng', 10, 7);
            $table->decimal('lat', 10, 7);
            $table->boolean('isConfirmed')->default(0);
            $table->boolean('isHot')->default(0);
            $table->boolean('isVisible')->default(0);
            $table->boolean('isFeatured')->default(0);
            $table->timestamp('lastScrapeForContacts')->nullable();
            $table->timestamps();
        });

VenueReview migration:

Schema::create('venuereviews', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('venue_id')->index();
            $table->foreign('venue_id')->references('id')->on('venues')->onDelete('cascade')->onUpdate('cascade');
            $table->unsignedInteger('user_id')->index();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->integer('rating');
            $table->text('body')->nullable();
            $table->boolean('isVisible')->default(0);
            $table->boolean('isFeatured')->default(0);
            $table->boolean('isConfirmed')->default(0);
            $table->timestamps();
        });
Dec
10
5 months ago
Activity icon

Started a new Conversation Problem Passing RenderItem To FlatList As Prop In React-native

Hi everybody, I want to make a reusable FlatList component, for this I need to pass renderItem function as a prop to my reusable component but for some reason the renderItem components are not showing up.

In my parent component:


const itemView = ({ item, index }) => 
    {
        return <ReviewCard3 item={item} />
    };

<RList1 onEndReachedAction={venueReviewStore.list} data={data} renderItem={itemView}></RList1>

In my children (reusable list component

const { ...rest } = props;

<FlatList  style={{ flex:1,backgroundColor:'rgb(235,235,235)'}}  data={data} keyExtractor={item => item.id.toString()} extraData={loader}
        onEndReached={ ()=>{ onEndReached() } } onEndReachedThreshold={0.1}
        {...rest}
        />

What am I doing wrong?

Dec
09
5 months ago
Activity icon

Started a new Conversation Checking Next OpeningHours In Array With Javascript

I have an array representing buinessTimes of a restaurant, knowing the current index of the current day, lets say 5, representing saturday and the next opening day being monday, I want to show the next time the venue will open.

I'm using a for loop to check this but the problem is the loop ends and I don't know how to go back to the start of the array...

const [openingTimes, setOpeningTimes] = useState([
        {day:'lunes', hours:    [ { opens: '09:00', closes: '17:30' }, { opens: '21:00', closes: '03:00' } ]},
        {day:'martes', hours:    [ { opens: '09:00', closes: '17:30' }, { opens: '21:00', closes: '03:00' } ]},
        {day:'miƩrcoles', hours:    [ { opens: '09:00', closes: '17:30' }, { opens: '21:00', closes: '03:00' } ]},
        {day:'jueves', hours:    [ { opens: '09:00', closes: '17:30' }, { opens: '21:00', closes: '03:00' } ]},
        {day:'viernes', hours:    [ { opens: '09:00', closes: '17:30' }, { opens: '21:00', closes: '03:00' } ]},
        {day:'sabado', hours:    [ { opens: '09:00', closes: '17:30' }, { opens: '21:00', closes: '03:00' } ]},
        {day:'domingo', hours:    [ ]},
    ]);

const currentDayIndex = 5;
let foundNextOpeningDay = false;

for(var i=0; i<openingTimes.length; i++)
{
                if(i > weekdayIndex && openingTimes[i].hours.length > 0 && !foundNextOpeningDay)
                {
                    let willOpenNext = openingTimes[i].hours[0].opens;
                }
}
Activity icon

Started a new Conversation Weird Output When Trying To Format A String With Moment.js And Calculating Time Difference

I'm passing a string representing a 24 hour datetime like HH:mm, I'm trying to format it in order to compare and get remaining time between two datetimes, however I'm getting a very weird output and my function is returning NaN when outputing time difference..

let closingTime = '21:00',
let remaining = remainingHourAndMinute(closingTime);

const remainingHourAndMinute = (endDate) =>
    {
        var now = moment().format('HH:mm');
        console.log('now',now);
        var end = moment(endDate, 'HH:mm'); //Here I format the string to a moment object
        console.log('end',end);
        var duration = moment.duration(end.diff(now));

        //Get Days and subtract from duration
        var days = duration.asDays();
        duration.subtract(moment.duration(days,'days'));

        //Get hours and subtract from duration
        var hours = duration.hours();
        duration.subtract(moment.duration(hours,'hours'));

        //Get Minutes and subtract from duration
        var minutes = duration.minutes();
        duration.subtract(moment.duration(minutes,'minutes'));

        //Get seconds
        var seconds = duration.seconds();

        return hours > 0 ? hours+' horas y '+minutes+' minutos' : minutes+' minutos'; 
    };

This is what the console logs.

now 18:56
end "2020-12-09T20:00:00.000Z"
diff NaN minutes

Notice how the now time is a normal 24h datetime but end is such a weird parsed format, that's why I think my function is giving me NaN, because I'm comparing dattimes in different formats...

Activity icon

Started a new Conversation React Native: Trucate Text If Bigger Than Width Percentage

Hi everybody, in react native having a Text component with a given width in percentages how can I trucate that text with ellipsis if the resulting text is bigger than the given width?

<Text style={{width:'50%'}}>{ dynamic.text }</Text>

Thanks in advance.

Dec
03
5 months ago
Activity icon

Started a new Conversation React Native: Lodash Debounce Not Working?

Hi everybody, in my react native app I have a textinput for users to type and search, I want to use lodash debounce so that the automatice search is more performant but for some reason my results array is never populated and I'm not console login anything either...

Funny thing is if instead of changing state inside debounce action I change results array without debouncing it actually works right but doing a search each key change seems like a lot, is it? I'm not doing fetches but a javascript search which would be better performance wise.

Here is my code:

const handleSearchChange = (value)=>
    {
        setSearch(value);
        let results = filterSearch(allProducts);
        
        _.debounce(e => {
            console.log('Debounced search:', e);
            setResults(results);
        }, 1000);
        
        //setResults(results);
    }

<TextInput onChangeText={value => handleSearchChange(value)} value={search} style={{ width:'90%', height:'100%', borderRadius:5, padding:10, color:'rgb(68,68,68)',fontSize:16, backgroundColor:'rgba(255,255,255,1)', alignItems:'center' }} placeholder="Donde vamos hoy?"></TextInput>
Dec
02
5 months ago
Activity icon

Started a new Conversation React Native: Dynamic Image Require In Component?

Hi everybody, I'm trying to show a randomly generated image in my Image component, however I'm getting the following error:

invalid call at line 58:require(getRandomImage())

My component:

const [ randomImages, setRandomImages ] = useState([
        //require('../assets/images/aranda.jpg'),
        require('@assets/images/bilmore.jpg'),
        require('@assets/images/cachalote.jpg'),
        require('@assets/images/lola.jpg'),
        require('@assets/images/meson.jpg'),
        require('@assets/images/paloma.jpg'),
        require('@assets/images/picasso.jpg'),
        require('@assets/images/pimpi.jpg'),
        require('@assets/images/tintero.jpg'),
        require('@assets/images/tropicana.jpg'),
    ]);

const getRandomImage = () =>
    {
        return randomImages[rand(0,9)];
    };

    const rand = (min, max) => 
    {
        return Math.floor(Math.random() * (max - min)) + min;
    }


<Image style={{ width:'100%', height:200,}}  resizeMode="cover" source={require(getRandomImage())}/> 
Dec
01
5 months ago
Activity icon

Started a new Conversation React Native: FlatList Not Updating After Pushing New Items To Array

Hi everybody, I have a reusable FlatList component which triggers an API call after I scroll to bottom of list, after that I update the data property pushing new items into array but my FlatList is not updating, only items showing are the initial ones...

The important part is here, where I clone my data array with lodash and push new items, flatlist not updating tho...

try 
            {
                let response = await http.get(env.BASE_URL+'/api/venuereviews', { page : 1, paginate : 3});
                var clone = _.cloneDeep(data);
                clone.push(response.data.data.data);
                setData(clone); //Updating data but list is not re-rendering
            } 
            catch (error)
            {
                throw error;
            }

Here is my full FlatList component:

import _ from 'lodash';

export default RList1 = observer((props) => 
{
    
    const [ data, setData ] = useState([]);
    const { ...rest } = props;

    useEffect(() => {
        console.log('RList1 mounted');
        if(props.data && props.data.length > 0)
        {
            var clone = _.cloneDeep(props.data);
            setData(clone);
        }
    }, []);

    const onEndReached = async () =>
    {
            try 
            {
                let response = await http.get(env.BASE_URL+'/api/venuereviews', { page : 1, paginate : 3});
                var clone = _.cloneDeep(data);
                clone.push(response.data.data.data);
                setData(clone); //Updating data but list is not re-rendering
            } 
            catch (error)
            {
                throw error;
            }
    };

    
    return(
    <View style={{ flex:1 }}>
        <FlatList  style={{ width:'100%',backgroundColor:'rgb(245,245,245)'}}  data={data} keyExtractor={item => item.id.toString()}
        onEndReached={ ()=>{ onEndReached() } }
        {...rest}
        />
    </View>
    );
        

});

In parent :

const itemView = ({ item, index }) => 
    {
        return <ReviewCard3 item={item} />
    };

<RList1 onEndReachedAction={venueReviewStore.list} data={reviews} renderItem={itemView}></RList1>
Nov
28
5 months ago
Activity icon

Started a new Conversation Issue With Custom Header (scene.route Is Undefined)

Hi everybody, I'm trying to have a custom header component in react native navigation 5, however I'm getting the following error:

TyperError: undefined is not an object (evaluating 'scene.route')

In my component:

export default CustomHeader2 = (props) => 
{
  const {scene, previous, navigation } = props;


    return (
    <View style={{ width:'100%',height:50, flexDirection:'row', alignItems:'center', justifyContent:'space-between', backgroundColor:'white' }}>
        <View style={{ height:50, flexDirection:'row', alignItems:'center' }}>
        {previous ? 
        (<TouchableOpacity onPress={ ()=>{ navigation.goBack() } } style={{ width:50, height:'100%',flexDirection:'column',alignItems:'center', justifyContent:'center' }}>
            <MaterialCommunityIcon name="arrow-left" style={{ color:'black', marginRight:0, fontSize:30 }}/>
        </TouchableOpacity>)
        :null
        }
        <Text style={{ fontSize:18, color:'rgb(68,68,68)',fontWeight:'bold' }}>{ scene.route.params.venue.name }</Text>
        </View>
    </View>
    );

};

In my stack:

<Stack.Screen
            name="VenueCard8"
            component={VenueCard8}
            headerShown={true} 
            options={({ route }) => ({ title: route.params.venue.name, header: () => (<CustomHeader2></CustomHeader2>) })}
            
        />
Nov
26
5 months ago
Activity icon

Started a new Conversation React: Issues Updating Array With UseState Hook

Hi everybody, I have an array of objects representing the opening hours of a business, now the user is able to change the open and closing time of specific days and shifts, adding new shifts and removing them too, I'm still a newb at react and state hook with arrays and my changes are not reflected in my views.

The actions I'm trying to do are:

Updating a specific item property in array

openingTimes[dayIndex].hours[splitIndex].opens = selectedHour+':'+selectedMinute;

Removing last item of array

openingTimes[i].hours.pop();

Adding an item to array

openingTimes[i].hours.push({ opens: 'Abre', closes: 'Cierra' });

And the openingTimes array of objects for reference:

const [openingTimes, setOpeningTimes] = useState([
        {day:'monday', hours:    [ { opens: 'Abre', closes: 'Cierra' } ]},
        {day:'tuesday', hours:    [ { opens: 'Abre', closes: 'Cierra' } ]},
        {day:'wednesday', hours:    [ { opens: 'Abre', closes: 'Cierra' } ]},
        {day:'thursday', hours:    [ { opens: 'Abre', closes: 'Cierra' } ]},
        {day:'friday', hours:    [ { opens: 'Abre', closes: 'Cierra' } ]},
        {day:'saturday', hours:    [ { opens: 'Abre', closes: 'Cierra' } ]},
        {day:'sunday', hours:    [ { opens: 'Abre', closes: 'Cierra' } ]},
    ]);
Activity icon

Started a new Conversation React Native: SelectedDays.includes Is Not A Function

Hi everybody, I'm new to react-native and I have an input where I can choose multiple days of a week, if I click on a day which is alreadyAdded the day is removed from selectedDays array, however when I click on a day I get the following error:

TypeError: selectedDays.includes is not a function. (In selectedDays.includes(index+1) selectedDays.includes is undefined

My code:


const [ dayOptions, setDayOptions ] = useState([ 'Lunes','Martes','Miercoles','Jueves','Viernes','Sabado','Domingo']);
    const [ selectedDays, setSelectedDays ] = useState([1]);


const clickedDay = (id)=>
    {
        const index = selectedDays.indexOf(id);
        if (index > -1)
        {
            setSelectedDays(selectedDays.splice(index, 1));
        }
        else
        {
            setSelectedDays(selectedDays.push(id));    
        }
    }


<View style={{ width:'100%',height:45,flexDirection:'row',alignItems:'center',flexWrap:'nowrap', justifyContent:'space-between' }}>
                        {dayOptions.map((option,index) => {return (
                        <TouchableOpacity  key={option.title} onPress = {() => {clickedDayOptions(index+1) }} style={{ width:'13.2%', height:'100%', flexDirection:'row', alignItems:'center',justifyContent:'center', borderRadius:5,borderWidth:1, borderColor:'rgba(0,0,0,0.2)', ...selectedDays.includes(index+1) ? { backgroundColor: 'rgb(255,52,89)' } : { backgroundColor:'white' }, }}>
                            <Text style={{ fontWeight:'bold',fontSize:14, ...selectedDays.includes(index+1) ? { color: 'white' } : { color:'rgb(68,68,68)' }, }}>{ option }</Text>
                        </TouchableOpacity>)
                    })}     
</View>

I tried changing includes for indexOf() > 1 and I get the same error, I usually get this when it's not an array but I defined selectedDays as an array in hooks...

Activity icon

Started a new Conversation React Native: Children Not Reacting To Parent Prop Change

I have a custom modal component where I pass a isVisible prop, this prop comes from it's parent state property state, now in the modal (child component) I can eit and event and react to it in the parent, changing the value in the parent should effect the child and the modal should close now, but the modal is not closing!

Parent:


const [ modalIsVisible, setModalIsVisible ] = useState(false);

const handleCloseModal = ()=>
    {
        setModalIsVisible(false); Alert.alert('caca');
    };

<ReviewFormModal1 onCloseModal={ ()=>{ handleCloseModal() } } isVisible={modalIsVisible}></ReviewFormModal1>

Child:


const onClosePress = () => 
    {
        props.onCloseModal();
    }

<Modal isVisible={props.isVisible} style={styles.modal}>
                <TouchableOpacity onPress={ ()=>{ onClosePress() } } style={{ flex:1 }}></TouchableOpacity>
</Modal>

I'm still a react-native newb (coming from vue which imo is much easier), but afaik this is the proper way to react to prop changes in the parent, props being always top-down.

Nov
25
5 months ago
Activity icon

Started a new Conversation React Native: RenderItem Component To Custom FlatList As A Prop? (like Vue Slots)

Hi everybody, I want to have a reusable FlatList component, basically a wrapper I can pass a custom component as an item to render, and I want to pass this component as props, this is easily done in vue..js with scoped/slots.

Is there a way to do this in react native?

<View style={{ flex:1 }}>
        <FlatList  style={{ width:'100%'}}  data={props.data} keyExtractor={item => item.id.toString()}
            renderItem={({ item, index }) => 
            <PropComponent item={item}></PropComponent>}
        />
    </View>

In example above PropComponent would be passed to CustomFlatList like this:

<CustomFlatList>
     <PropComponent></PropComponent>
</CustomFlatList>
```
Nov
23
5 months ago
Activity icon

Started a new Conversation Library For Fcm Push Notifs With Laravel Backend In React Native?

I want to implement scheduled/custom-per-user push notifications from my laravel php backend to my react-native app (no expo), I want to hear from you what is the best and easiest, future proof library for achieving this, some example code would be great too since I haven't implemented this before.

Thanks in advance.

Nov
17
5 months ago
Activity icon

Started a new Conversation Laravel Passport Social Grant In React-native App, Examples?

Hi everybody, I want to implement laravel passport + social grant (Google, Facebook, Twitter login):

lib: https://github.com/coderello/laravel-passport-social-grant

Into my react-native app created with react CLI, I suspect I may have to use a webview in my app in order to login users but I'd love for other devs to shed some light on how to achieve this since right now I'm pretty lost...

Nov
16
5 months ago
Activity icon

Started a new Conversation Shift Elements In An Array N Positions

Hi everybody, I have an array of objects, given an index I want to move the object of given index to the first position and then change the order of the elements in the array accordingly!

I'll try to give you an example:

Given the following array and the index 3 , thursday:

const openingTimes =
    [
        {day:'monday', hours:    [ { opens: '09:00', closes: '17:30' } ]},
        {day:'tuesday', hours:    [ { opens: '09:00', closes: '17:30' } ]},
        {day:'wednesday', hours:    [ { opens: '09:00', closes: '17:30' } ]},
        {day:'thursday', hours:    [ { opens: '09:00', closes: '17:30' } ]},
        {day:'friday', hours:    [ { opens: '09:00', closes: '17:30' } ]},
        {day:'saturday', hours:    [ { opens: '09:00', closes: '17:30' } ]},
        {day:'sunday', hours:    [ { opens: '09:00', closes: '17:30' } ]},
    ];

The resulting array would be the following:

const modifiedOpeningTimes =
    [
        {day:'thursday', hours:    [ { opens: '09:00', closes: '17:30' } ]},
        {day:'friday', hours:    [ { opens: '09:00', closes: '17:30' } ]},
        {day:'saturday', hours:    [ { opens: '09:00', closes: '17:30' } ]},
        {day:'sunday', hours:    [ { opens: '09:00', closes: '17:30' } ]},       
        {day:'monday', hours:    [ { opens: '09:00', closes: '17:30' } ]},
        {day:'tuesday', hours:    [ { opens: '09:00', closes: '17:30' } ]},
        {day:'wednesday', hours:    [ { opens: '09:00', closes: '17:30' } ]}, 
    ];
Nov
09
6 months ago
Activity icon

Started a new Conversation Get Most Favorited (many To Many) Records In Laravel

Hi everybody, I have an app where users can favorite venues, this is done via a many to many relationship with a "favorites" pivot table.

Now I want to retrieve the top 10 most times favorited Venues with Eloquent.

My models:

//User model

public function favorites()
    {
        return $this->belongsToMany('App\Models\Venue', 'favorites', 'user_id', 'venue_id')->withTimeStamps();
    }

//Venue model

public function favorites()
    {
        return $this->belongsToMany('App\Models\User', 'favorites', 'venue_id', 'user_id')->withTimeStamps();
    }

Thanks in advance!

Activity icon

Started a new Conversation Help Transforming Sql Sentence Into Laravel's DB:raw

Hi everybody, I want to get venues inside a radius in my laravel/mysql backend, I have a sql sentence which I think would help me but I need to transform it into something Eloquent could understand, I could do something like

Venue::select(DB:raw( /SENTENCE GOES HERE/)

But I don't know how to transform my sql syntax into a properly formatted string, here is my code:

        $latitude = $request->input('lat') ?? 36.720240;
        $longitude = $request->input('lng') ?? -4.405770;
        
        $point = point($latitude, $longitude);
        $radius = 0.1;
        $polygon = ST_Buffer($point, $radius);

        $venues = [];

        //How to transform this thing right here into DB::raw or something laravel can understand
        select v.name, st_distance_sphere(point(v.lat, v.lng), point($lat, $lng)) as dist
        from venues v
        where st_within(point(v.lat, v.lng), $polygon)
        order by dist
        limit 50
Activity icon

Started a new Conversation Firebase Auth/social Login With Laravel User Models In React Native

Hi everybody, I'm working on a react-native app where the backend is done in laravel, at first I am using Sanctum for protecting my api routes.

However, I have decided I want to have my users being able to register with their facebook/google accounts, and for this I came up with firebase for react-native, it has both email and social login sdks and much more.

But I'm so confused, how can i let my users register/login with firebase social/email logins and link them with the users in my laravel/mysql database?

Can anyone shed some light on me?