chrisgrim

chrisgrim

at Self Employed

Member Since 1 Year Ago

Petaluma

Experience Points
25,310
Total
Experience

4,690 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
133
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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
25,310 XP
Nov
09
3 days ago
Activity icon

Replied to Laravel Question About Wildcard Backend Magic

@snapey This is for when they are creating the event so I want the slug to represent the event but I don't need to change the slug as they are building out the event. But you are correct I don't want them to change the slug for SEO purposes so I definitely don't want them to be able to edit it afterwards.

I am going to wait until I approve the event to generate a slug based off the name only at that one time.

Thanks so much for giving me the idea.

Activity icon

Replied to Laravel Question About Wildcard Backend Magic

Hi @sinnbeck I just gave fallback routes and try by putting

Route::fallback(function () {
    return 'test';
});

in my routes at the bottom. If I go to websitename.com/random it works and shows test. However if I press the back button after changing the event slug I still get the 404 error.

Activity icon

Started a new Conversation Laravel Question About Wildcard Backend Magic

Hi,I am using a wildcard to load my events

Route::GET('/create-event/{event}/title', '[email protected]');

Then in my controller I use 

public function title(Event $event)
    {
        return view('create.title', compact('event'));
    }

to get the correct event based off the slug and return it. My question is in my app I allow the user to change the slug of the event. This works fine because I return the new slug and reload the page with that new slug. This works great but if they press the back button on the browser it tries to go back to the url with the original slug. This gives me a 404 error because it has been updated to the new slug. Is there a special way laravel deals with this?

Nov
04
1 week ago
Activity icon

Awarded Best Reply on Laravel Delete All Related Rows Not Working

I was able to get it working by adding this to my method

        $showDelete = $event->shows()->whereNotIn('date', $request->dates)->get();
        foreach($showDelete as $show){
            $show->tickets()->delete();
        }
        $event->shows()->whereNotIn('date', $request->dates)->delete();

It's not the cleanest but it works.

Activity icon

Replied to Laravel Delete All Related Rows Not Working

I was able to get it working by adding this to my method

        $showDelete = $event->shows()->whereNotIn('date', $request->dates)->get();
        foreach($showDelete as $show){
            $show->tickets()->delete();
        }
        $event->shows()->whereNotIn('date', $request->dates)->delete();

It's not the cleanest but it works.

Activity icon

Replied to Laravel Delete All Related Rows Not Working

I tried setting up an observer model just now and it still isn't deleting. In ShowObserver.php

use App\Show;

class ShowObserver
{

public function deleted(Show $show)
    {
        foreach ($show->tickets as $ticket)
            {
                $ticket->delete();
            }
    }

In my appserviceprovider

use App\Show;
use App\Observers\ShowObserver;
use Illuminate\Support\ServiceProvider;

   public function boot()
    {
        Show::observe(ShowObserver::class);
    }
Activity icon

Replied to Laravel Delete All Related Rows Not Working

Ok I gave that a shot what snapey suggested

class Event extends Model
{
    use Searchable, Favoritable, SoftDeletes;

    public static function boot ()
    {
        parent::boot();

        self::deleting(function (Event $event) {

            foreach ($event->shows as $show)
            {
                $show->delete();
            }
        });
    }
class Show extends Model
{
    use SoftDeletes;

    public static function boot ()
    {
        parent::boot();

        self::deleting(function (Show $show) {

            foreach ($show->tickets as $ticket)
            {
                $ticket->delete();
            }
        });
    }

and then in my method

$event->shows()->whereNotIn('date', $request->dates)->delete();

but it still only deletes the show and not the associated tickets. Do you see anything missing?

Activity icon

Replied to Laravel Delete All Related Rows Not Working

Hi @jlrdw That tool looks perfect. I am worried about being dependant on too many plugins though. From what I see online this should be a relatively simple thing to code. If I use that tool then I am stuck further down the line if it breaks.

Activity icon

Replied to Laravel Delete All Related Rows Not Working

I am doing soft deletes so I didn't know if I had to setup cascade on delete in my migration table

Activity icon

Started a new Conversation Laravel Delete All Related Rows Not Working

Hi, I have been looking up how to delete related rows and I am struggling to get it working. I have models Show and Tickets. I want to delete all tickets associated with shows when I delete a show. In my method I have

$event->shows()->whereNotIn('date', $request->dates)->delete();

and in my Show.php file I have

public function delete()
    {
      $this->tickets()->delete();
      return parent::delete();
    }

The show is deleted but the tickets still remain. The only thing I can think is that it is because I am calling the delete on $event->shows? If so, would I need to put the delete function on my Event.php file?

Nov
01
1 week ago
Oct
31
1 week ago
Activity icon

Replied to Looking For A Good Vue DatePicker Plugin

As far as I can see, that datepicker only does single dates. (Am I missing it?) I was hoping to find one that does multiple date entries.

Activity icon

Started a new Conversation Looking For A Good Vue DatePicker Plugin

I need a very robust date selection tool. I have a site with events and Id love to have my users create events and then beable to select different show dates. I started off using https://flatpickr.js.org/ which I love. It's so simple and fast and easy to use. However, the big drawback is that it saves dates as a string

 “2019-10-31 00:00:0, 2019-11-03 00:00:0, 2019-11-10 00:00:0, 2019-11-04 00:00:0”.

This means to store it in Laravel I have to convert it to an array. This causes a big pain saving to the database because if a user updates their dates I have to completely delete all the previously stored dates and resave all of the new dates.(The show id is usesless) I also want to attach ticket prices to each date which I would have to delete as well with any updates.

I love how Vue MultiSelect uses objects and was hoping there was a free/not too expensive date selector that worked in a similar way.

Activity icon

Replied to Cookies Is Always One Request Behind

It does! @snapey and @sinnbeck I wish I could give multiple best answers! You guys both rock

Activity icon

Replied to Cookies Is Always One Request Behind

Oh Yeah! When I monitor the redis-cli and reload the page I see

1572557706.267854 [0 127.0.0.1:60457] "SELECT" "0"
1572557706.268007 [0 127.0.0.1:60457] "GET" "everythingimmersive_database_everythingimmersive_cache:6xCacpicWbddSiBcE4WWHzG9HpX8JUhktoaOTFx1"
1572557706.268811 [0 127.0.0.1:60457] "SETEX" "everythingimmersive_database_everythingimmersive_cache:6xCacpicWbddSiBcE4WWHzG9HpX8JUhktoaOTFx1" "7200" "s:505:\"a:6:{s:6:\"_token\";s:40:\"fgnvoXeIDDjm0AZwlE4PETYu3ZgwIt9PAKTi4E6t\";s:3:\"url\";a:0:{}s:9:\"_previous\";a:1:{s:3:\"url\";s:28:\"https://ei.test/index/search\";}s:6:\"_flash\";a:2:{s:3:\"old\";a:0:{}s:3:\"new\";a:0:{}}s:50:\"login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d\";i:1;s:15:\"searchDataStore\";a:6:{s:2:\"id\";i:14122;s:4:\"name\";s:15:\"Los Angeles, CA\";s:8:\"latitude\";s:11:\"34.11390000\";s:9:\"longitude\";s:13:\"-118.40680000\";s:10:\"created_at\";s:19:\"2019-10-31 21:16:09\";s:10:\"updated_at\";s:19:\"2019-10-31 21:16:09\";}}\";"
1572557706.271188 [0 127.0.0.1:60457] "GET" "everythingimmersive_database_everythingimmersive_cache:6xCacpicWbddSiBcE4WWHzG9HpX8JUhktoaOTFx1"

so I guess it does use redis when I use session. Very cool!

Activity icon

Replied to Cookies Is Always One Request Behind

Really?! Is that the same for redis? If I do

Redis::set('searchDataStore', json_encode($request->all()));

that is unique to the user?

Activity icon

Replied to Cookies Is Always One Request Behind

@sinnbeck Sorry, that didnt return anything :(

@snapey I see. I have already setup Redis, but I have an issue with sessions and redis. What do I save as the key? The user does not have to be logged in so I have nothing unique to name the key ie $user->id

Activity icon

Replied to Cookies Is Always One Request Behind

Hi @snapey , I need to store data so I can pass it from one vue component to another during a page reload. I do an axios post

axios.post('/search/storedata', this.searchBoxInput);

//then I load the search page

window.location.href = '/index/search';

that points to a webroute

Route::GET('/index/search', '[email protected]');

which points to the method

public function index()
    {
        $searchedevents = request()->cookie('search');
        return view('searches.search',compact('searchedevents'));
    }

I pass that back into my Vue component with a v-bind. This works great except it shows the previous search :)

Activity icon

Started a new Conversation Cookies Is Always One Request Behind

Hi, I am testing out cookies and have a question about how they work. I am saving data to my cookies like so

public function searchDatastore(Request $request)
    {
        Cookie::queue(cookie('search', json_encode($request->all()), $minute = 10));
    }
public function index()
    {
        $searchedevents = request()->cookie('search');
        return view('searches.search',compact('searchedevents'));
    }

With the above code, I always get back the previous search. If I search for texas it will show the previously stored search. If I search afterwards for miami, then it will show texas on return. Is this normal behavior? If I do a return $request in my searchDatastore it is the correct location.

Activity icon

Replied to Issues Combining Two Arrays When Saving To Database

Yeah for now that is exactly what I want it to do. Thanks!

Activity icon

Replied to Issues Combining Two Arrays When Saving To Database

@nakov That worked, thanks so much again for your help. Is there a cleaner way to write this?

Activity icon

Started a new Conversation Issues Combining Two Arrays When Saving To Database

I understand what I need to do but I can't figure out how to do it. I have events shows and tickets. Events hasMany shows and each show hasMany tickets. In my request I am sending

dates: ["2019-11-06 00:00:0", "2019-11-05 00:00:0", "2019-11-04 00:00:0"]
0: "2019-11-06 00:00:0"
1: "2019-11-05 00:00:0"
2: "2019-11-04 00:00:0"

tickets: [{name: "General", price: ".00"}, {price: ".00", name: "VIP"}]
0: {name: "General", price: ".00"}
1: {price: ".00", name: "VIP"}

In my controller I am trying to store each show to the event and then as I create each show I try to store the tickets to that show.

public function store(ShowStoreRequest $request, Event $event)
    {
     
        foreach( $request->dates as $date) {

            $show = Show::create([
                'date' => $date,
                'event_id' => $event->id
            ]);


            foreach ($request->tickets as $ticket) {
                Ticket::create([
                    'show_id' => $show->id,
                    'name' => $ticket->name,
                    'ticket_price' => $ticket->price
                ]);
            }
        };
}

I'm getting the error Trying to get property 'name' of non-object", exception: "ErrorException",}

Activity icon

Replied to Redis Data Not Saving After Page Reload

@christophharms Thank you so much!! The redis-cli monitor was exactly what I was looking for. I do have one question. I was redis to update only when I hit the pages where I call it. However any page I load on my site redis updates with

1572538537.439310 [0 127.0.0.1:50748] "GET" "everythingimmersive_database_everythingimmersive_cache:S0CZaPWuvzSjegEirNy5f3bGR17XvMGqkncBu8Q0"
1572538538.947287 [0 127.0.0.1:50760] "SELECT" "0"
1572538538.947394 [0 127.0.0.1:50760] "GET" "everythingimmersive_database_everythingimmersive_cache:jhH3i8119egjSJm2m6MZ3vtdyRNDjwBWU31IsC6p"

What is happening here?

Oct
29
2 weeks ago
Activity icon

Started a new Conversation Redis Data Not Saving After Page Reload

Hi, I am trying to save data using redis as a user enters dates. I installed redis locally using brew and installed composer require predis/predis. I have in my methods:

public function tempStore(Event $event, Request $request)
    {
        Redis::set('test', json_encode($request->all()));
    }
    public function getTempStore(Event $event)
{
    return Redis::get('test');
}

If I stay on the same page it returns the data when I do an axios post to tempStore and then an axios get from getTempStore. However if I reload the page and try to do an axios get it returns an empty array. Is there a way to see the data stored in my redis database? I am not really sure how to trouble shoot this.

Oct
28
2 weeks ago
Activity icon

Replied to Question About How Laravel Sessions Works

Ohhh I see! Thanks

Activity icon

Replied to Question About How Laravel Sessions Works

So you are saying that even though I have

'driver' => env('SESSION_DRIVER', 'redis'),

it is still using file?

Activity icon

Started a new Conversation Question About How Laravel Sessions Works

Hi, I am storing data to my session and I am trying to understand how it works. If I set it up like this

       public function tempStore(Event $event, Request $request)
    {
        Session::put($event->id, $request->all());
    }
    public function getTempStore(Event $event)
    {
        return Session::get($event->id);
    }

and in my session.php file I have

   'driver' => env('SESSION_DRIVER', 'redis'),

everything seems to work fine. However, when I go look at tutorials people all show creating a migration table for redis or memcache. I haven't created a migration table but it seems to be working still.

Oct
25
2 weeks ago
Activity icon

Replied to How To Pass Data With Vue Between Pages

The problem with this method is the content just gets pushed down right? I am trying to send search result data through. The problem is submitting with ajax.

Oct
24
2 weeks ago
Activity icon

Replied to How To Pass Data With Vue Between Pages

Also I realized with Vue Portal I would have to have a v-if="show on user search" on every page which seems like an inefficient way to work.

Activity icon

Replied to How To Pass Data With Vue Between Pages

Hi @nolros So I tried this.$router.go('/newpage') and all it does is reload the current page. I have looked into it and it looks like Vue Router changed the way go works. Is there any way at all to use Router to redirect to a new url with data? As far as I can see there is not.

Vue Portal does seem like it will work but I worry about speed. If I am loading all my returned events using Vue Portal in the body below could that cause a website loading hit?

Oct
23
2 weeks ago
Activity icon

Replied to How To Pass Data With Vue Between Pages

Hi @nolros Thanks so much for your message. So it turns out I did the not recommended way. I wanted to use the Vue router but I am using laravel web routes as my navigation (not doing a SPA) and I couldn't get Vue router to actually redirect to a new url. The solution I finally figured out was number 3/ passing it as a url. Then in the new page I grab the info using the $route.query. I would be soooo interested in learning if there is a way to use Vue router to redirect. Here is my current Vue Navbar search file:

<template>
    <div class="nav-search">
        <div class="nav-search__input">
            <multiselect 
            v-model="searchBoxInput" 
            :options="options" 
            open-direction="bottom"
            placeholder="Try Los Angeles"
            label="name"
            :loading="isLoading"
            :show-labels="false"
            :internal-search="false"
            :options-limit="30" 
            :limit="5"  
            track-by="name" 
            @search-change="asyncFind" 
            :show-no-results="false"
            :allow-empty="false">
            <template slot="selection" slot-scope="{ values, search, isOpen }"><span class="multiselect__single" v-if="values.length &amp;&amp; !isOpen">{{ values.length }} options selected</span></template>
            </multiselect>  


            <button @click.prevent="searchEvents()">Search</button>     
        </div>

            
    </div>
</template>

<script>
import Multiselect from 'vue-multiselect'
import format from 'date-fns/format'
import _ from 'lodash'

export default {

    components: { 
        Multiselect,
    },

    computed: {
        urlLoc: function () {

        return `/index/search?name=${this.searchBoxInput.name}&latitude=${this.searchBoxInput.latitude}&longitude=${this.searchBoxInput.longitude}`;
        },

    },


    data() {
        return {
            searchBoxInput: _.has(this.$route.query, 'latitude') ? this.$route.query : [],
            options: [],
            isLoading: false,
        }
    },

    methods: {


        asyncFind (query) {


            axios.get('/api/city/search', { params: { keywords: query } })
            .then(response => {
              
                this.options = response.data;

            })
            .catch(error => {
                console.log(error)
            });
        },


        searchEvents(post) {


            //add the searched date value to the location search

            if(_.has(this.searchBoxInput, 'latitude')) 
            {
                window.location.href = this.urlLoc;

            };


        },

};
</script>

and then when it redirects to /index/search?latitude=4.343 etc... and in my vue page body file I have

<template>
    <div>
        <h2>Our Latest Events</h2>
        <div id="app">
            <div id="grid-section">
                <div v-for="event in events">
                    <event-listing-item :event="event"></event-listing-item>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import _ from 'lodash';
    import Multiselect from 'vue-multiselect';
    import format from 'date-fns/format';
    import { mapGetters } from 'vuex'


    export default {


        components: {
            Multiselect,
        },

        computed: {
            ...mapGetters([
                'events'
            ]),
        },

        name: "searchEvents",

        data() {
            return {
                value: '',
                list: [],
                price: '',
                eventName: '',
                location: '',
                searchObject: this.initializeSearchObject(),
            }
        },

        methods: {

            initializeSearchObject() {
                return {
                    latitude: '',
                    longitude: '',
                }
            },
        
            updateFilter() {

                _.extend(this.searchObject, this.$route.query);

                this.$store.dispatch('searchEvents', this.searchObject);

            },

        },

        mounted() {
            
            this.updateFilter();

        }

    };
</script>

dispatch searchEvents then fires

        searchEvents({commit}, event) {
            axios.post('/api/search', event)
                .then(res => {
                    commit('SEARCH_EVENTS', res.data)
                }).catch(err => {
                console.log(err)
            })
        },

which finally passes the data to my vuex event variable. Now that I write this out it does seem like a lot of steps but when I tried to use this.$router.push to go to /index/search page it didn't work because I am not doing a SPA. Thank you so much for any help.

Oct
22
3 weeks ago
Activity icon

Replied to Cleaner Way To Do If() Statements?

I like how clean that looks a lot!

Activity icon

Started a new Conversation Cleaner Way To Do If() Statements?

In my code I have a nav search that allows a user to search locations, organizers or events all in one input. This means before I submit I have to check what was entered. Currently I am doing

if(_.has(this.searchBoxInput, 'latitude') && _.has(this.searchDateRange, 'start')) 
            {
                window.location.href = this.urlLocDate;

            } else if (_.has(this.searchBoxInput, 'latitude')) {

                window.location.href = this.urlLoc;

            } else if (_.has(this.searchBoxInput, 'closingDate')) {

                window.location.href = `/events/${this.searchBoxInput.slug}`;

            } else if (_.has(this.searchDateRange, 'start')) {

                window.location.href = this.urlDate;
            }

It works but I am pretty sure this is the improper way to do this.

Activity icon

Replied to How To Pass Data With Vue Between Pages

Oh interesting! I was also thinking about adding is as a variable to the url address bar

Activity icon

Replied to How To Pass Data With Vue Between Pages

I know about emitting, but what about when it loads a new page and then wants to pass data?

Oct
21
3 weeks ago
Activity icon

Started a new Conversation How To Pass Data With Vue Between Pages

Hi, I have a nav bar in my application that has a search function. The nav bar is a vue component and the main body of my site is a vue component. My goal is to have a user beable to search in the nav bar from any point in the site and return a new page of results. The issue I am having is how to pass the data. I first tried using Vuex because I thought the data would be stored as I loaded the new html page. I discovered that Vuex worked great if I did a search when I was at '/'. However, if the user does a search when they are looking at a specific event '/event/namehere', then it would redirect back to the home page but without the variable passed. I then looked into Vue Router but I have already built out my application and I am not ready to make it an SPA. My issue is the the fact that I when I do an axios post I can only get back json.

How do I submit this axios search post from the navbar anywhere on the site and have it load the homepage with the results (without rebuilding my app as a SPA)?

Oct
19
3 weeks ago
Activity icon

Replied to Cleaner Way To Call Where() Without Using A Ton If() Statements

@nakov You are amazing! I knew there must be something like this out there :)

Activity icon

Started a new Conversation Cleaner Way To Call Where() Without Using A Ton If() Statements

Hi, I am using elastic search for my site and I am trying to clean up my search method. I have added all the filters I will be using to one method:

$events = Event::search('*')
            ->where('closingDate', '<=', 'now/d')
            ->where('category_id', '$request->category_id')
            ->whereGeoDistance('location_latlon', [$request->lon, $request->lat], '100km')
            ->whereBetween('dates.date', ['$request->first_date','$request->last_date'])
            ->get(); 

Obviously the user won't be using all of those filters so I am trying to figure out how to do it without calling a bunch of if ($request->searchname) etc. Something like this?

$events = Event::search('*')
    ->where('closingDate', '<=', 'now/d')
    ->if($request->category_id){where('category_id', '$request->category_id')}
    ->if($request->lon){whereGeoDistance('location_latlon', [$request->lon, $request->lat], '100km')}

Thanks so much

Activity icon

Replied to "numeric Value Expected"

The second issue gave me an error, so only the first one worked

Oct
18
3 weeks ago
Activity icon

Replied to "numeric Value Expected"

@piljac1 You are a genius!! Using

 ->whereGeoDistance('location_latlon', [floatval($request->longitude), floatval($request->latitude)], '100km')

did the trick! Thanks so much

Oct
17
3 weeks ago
Activity icon

Replied to "numeric Value Expected"

the response from both of those is

true
true
Activity icon

Started a new Conversation "numeric Value Expected"

Hi, If I run the following method I get an error saying numeric value expected

 public function searchLocation(Request $request)
    {   

        $radiusResults = Event::search('*')
            ->whereGeoDistance('location_latlon', [$request->longitude, $request->latitude], '100km')
            ->get();

        return response()->json($radiusResults);
    }

However if I run it like so

$radiusResults = Event::search('*')
            ->whereGeoDistance('location_latlon', [-90.0715323, 29.95106579999999], '100km')
            ->get();

        return response()->json($radiusResults);

I get the correct result back. If I do

return $request->latitude;

It returns 29.95106579999999. Is there something I'm missing? I tried

$lat = str_replace('"', "", $request->latitude);

but that still gave me the same error

Activity icon

Replied to LazyController Still Running Out Of Memory?

Hi Snapey, I am on my mac and I am not hosting the site online yet. The file is 55mb but I gave up with this method. Instead I am using https://github.com/Maatwebsite/Laravel-Excel and converting the .txt file to a csv. It's not the best method but it is working and not crashing.

Activity icon

Replied to LazyController Still Running Out Of Memory?

I closed all my windows and just ran the method and I got up to 10,219 rows!!! The crazy thing is I am looking at my memory and cpu and they aren't even moving really.

Activity icon

Replied to LazyController Still Running Out Of Memory?

That worked @sinnbeck but sadly it didn't fix the original problem ha! I tried running it again and this time it made it to 6,853 rows. The frustrating part is there is no error message that I can see.

Activity icon

Replied to LazyController Still Running Out Of Memory?

Hi @sinnbeck Sorry this is causing so much trouble! I am getting that first error again

General error: 1366 Incorrect integer value: 'l' for column 'geoNameId' at row 1 

and in my database I can see that it is entering 3 for the row instead of 345304. Here is the final code I am using

$cityList = LazyCollection::make(function () {
        $fp = fopen(storage_path('city.txt'), 'r');

        while ($line = fgets($fp)) {
                yield $line;
            }
        })->each(function($line) {

            foreach (explode("\t", $line) as $list) {
                
                CityList::Create([
                'geoNameId' => $list[0],
                'name' => $list[1],
                'latitude' => $list[4],
                'longitude' => $list[5],
                ]);
            }
        });
Activity icon

Replied to LazyController Still Running Out Of Memory?

Yeah on the error it selects this

'name' => $list[1],

but the geoname numbers are being incorrectly input. it shows 3, 3, etc but it should be 384785, 495939, 495939 etc

Activity icon

Replied to LazyController Still Running Out Of Memory?

I think it must be something else. If I do only the first one then I get

Uninitialized string offset: 1

It is actually adding stuff to my database.

name=
[0, 0, e, e, h, 2, . ] 
geonameid=
[3,3,0,0,0,4,1]
Activity icon

Replied to LazyController Still Running Out Of Memory?

If I do

foreach ($cl as $list) {
                CityList::Create([
                'geoNameId' => intval($list[0]),
                'name' => intval($list[1]),
                'latitude' => intval($list[4]),
                'longitude' => intval($list[5]),
                ]);
            }

I get the error

Uninitialized string offset: 1

I am not sure if this helps but if I add a return list to the foreach

foreach ($cl as $list) {
                return $list;
                CityList::Create([
                'geoNameId' => $list[0],
                'name' => $list[1],
                'latitude' => $list[4],
                'longitude' => $list[5],
                ]);
            }

and then below the lazycollection I do a return $cityList->first(); I get what looks correct

[
"3040051",
"les Escaldes",
"les Escaldes",
"Ehskal'des-Ehndzhordani,Escaldes,Escaldes-Engordany,Les Escaldes,esukarudesu=engorudani jiao qu,lai sai si ka er de-en ge er da,Эскальдес-Энджордани,エスカルデス=エンゴルダニ教区,萊塞斯卡爾德-恩戈爾達,萊塞斯卡爾德-恩戈爾達",
"42.50729",
"1.53414",
"P",
"PPLA",
"AD",
"",
"08",
"",
"",
"",
"15853",
"",
"1033",
"Europe/Andorra",
"2008-10-15\n"
]