jgravois

jgravois

Member Since 5 Years Ago

Memphis

Technical Manager at Universal Asset Management

Experience Points 111,555
Experience Level 23

3,445 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 1168
Lessons
Completed
Best Reply Awards 2
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

12 May
1 month ago

jgravois started a new conversation Zipping DO Spaces Files To Download

I need to zip all the files in a directory on DigitalOcean Spaces and force the download.

I found the ZIPPER package and locally it works very easily.

$files = glob(public_path('images/aircraft/*'));
Zipper::make(public_path('test.zip'))->add($files)->close();
return response()->download(public_path('test.zip'));

I set up a Spaces Disk in filesytem.php but can't figure out how to make it work the same way.

$docs = Storage::disk('spaces')->files($path);

gives me a list of files but that is paths to files not something to glob.

I've tried and tried with no luck and was hoping for a bit of assistance.

Thanks in advance.

11 Apr
2 months ago

jgravois left a reply on Vuex Update Doesn't Trigger Cascade

then for each child component, I pass via props

<field-editor  :form-id="currentForm.id"  label="Phone"  :xtant="currentForm.reporter_phone" field="reporter_phone"></field-editor>

jgravois left a reply on Vuex Update Doesn't Trigger Cascade

In the parent I import mapGetters and in computed

computed: {
            ...mapGetters([
                'currentUser',
                'currentForm',
                'currentFormLoaded',
                'formsLoaded'
            ])
        },

jgravois left a reply on Vuex Update Doesn't Trigger Cascade

Ok, I think I understand

This is the forms module in Vues

import Vue from 'vue';

const state = {
    currentFormId: null,
    formsLoaded: false,
    forms: []
};

const getters = {
    activeForms: state => (state.forms ? state.forms.filter(f => f.status < 4) : null),
    activeInvestigations: state => (state.forms ? state.forms.filter(f => f.status === 5) : null),
    closedForms: state => (state.forms ? state.forms.filter(f => f.status === 4) : null),
    currentForm: state => state.forms.find(form => form.id === parseInt(state.currentFormId)),
    currentFormLoaded: state => !!state.currentFormId,
    formsLoaded: state => state.formsLoaded,
};

const mutations = {
    FORMS_LOADED(state, payload) {
        state.formsLoaded = true;
    },
    SET_CURRENT_FORM(state, payload) {
        state.currentFormId = payload.id;
    },
    SET_FORMS(state, payload) {
        state.forms = payload;
    },
    UPDATE_RECORD_BY_FIELD(state, payload) {
        //console.log('PAYLOAD', payload);
        let idx = _.findIndex(state.forms, {id: state.currentFormId});
        state.forms.splice(idx, 1, payload);
    }
};

const actions = {
    getForms({state, commit}) {
        if(!state.formsLoaded) {
            let path = `/api/forms/quality`;
            axios.get(path)
                .then((rsp) => {
                    // console.log('ACTION getModelParts', rsp);
                    commit('SET_FORMS', rsp.data);
                    commit('FORMS_LOADED', {val: true});
                })
                .catch((err) => {
                    console.log('AXIOS ERR', err);
                });
        } // end if
    },
    setCurrentForm({commit}, payload) {
        commit('SET_CURRENT_FORM', payload);
    },
    updateField({commit}, payload) {
        //persist
        let path = `/api/forms/update_field/${payload.id}`;
        axios.patch(path, payload)
            .then((rsp) => {
                commit('UPDATE_RECORD_BY_FIELD', rsp.data);
            });
    }
};

export default { state, mutations, getters, actions }

jgravois left a reply on Vuex Update Doesn't Trigger Cascade

not sure what you are asking

jgravois started a new conversation Vuex Update Doesn't Trigger Cascade

I have an action that updates a database record and in the controller, I process the updated record to match the structure of the Vuex array element.

I have this MUTATION that I think should replace the updated record.

UPDATE_RECORD_BY_FIELD(state, payload) {
        //console.log('PAYLOAD', payload);
        let idx = _.findIndex(state.forms, {id: state.currentFormId});
        state.forms.splice(idx, 1, payload);
    }

The Console,Log IS returning the correct data.

However, the display is not updated without a full page refresh.

jgravois left a reply on Save Data Using Dynamic Field Name

@JBREUER95 - this worked once I got the values to post.

jgravois left a reply on Save Data Using Dynamic Field Name

message: "Too few arguments to function Illuminate\Database\Eloquent\Model::setAttribute(), 1 passed in /Users/jgravois/code/admin-adc/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 609 and exactly 2 expected"

jgravois started a new conversation Save Data Using Dynamic Field Name

I have a Vuex action that is used to update a record ... the action receives the record id, the field name and the new value.

Neither of these work ... suggestions???

public function update_field($id)
    {
        $form = QrfQualityForm::whereId($id)->first();
        $form->{request('field')} = request('val');
        $form->save();

        return new QualityFormListingResource($form);
    } // end function
public function update_field($id)
    {
        $form = QrfQualityForm::whereId($id)->first();
        $form[request('field')] = request('val');
        $form->save();

        return new QualityFormListingResource($form);
    } // end function
31 Jan
4 months ago

jgravois started a new conversation TRYING TO COPY ALL FILES FROM DISK TO DISK

After sending an email, I need to move an entire folder to another server which is our archive.

I am trying the following and when I return $src I get the array below and when I don't return $src, I get the error below

CODE

Route::get('/', function() {
        $randie = '1548863958';
        $src = Storage::disk('local')
            ->files("public/qrf/{$randie}");

        $dest = Storage::disk('store')->makeDirectory($randie);
        return $src;

        foreach($src as $file) {
            Storage::move($file, $dest);
        } // end foreach

        return Storage::disk('store')
            ->allFiles($randie);
    });

ARRAY

[
  "public/qrf/1548863958/gumbo.jpg",
  "public/qrf/1548863958/jasmine_smells_2019-01-29_Quality_Form.pdf"
]

ERROR

File already exists at path: 1

jgravois left a reply on Run ZSH Command From Laravel

LOOKS HORRIBLE!

I will start a new question

30 Jan
4 months ago

jgravois left a reply on Run ZSH Command From Laravel

even though the servers are on the same droplet at DigitalOcean ... I was thinking I could just copy via the filesystem

jgravois started a new conversation Run ZSH Command From Laravel

After sending an email, I need to move an entire folder to another server which is our archive.

I am trying this but it does nothing.

$randie = '1548863958';
$src = "/var/www/forms_farm/storage/app/public/qrf/{$randie}";
$dest = "/var/www/file_store/qrf/{$randie}";

exec("mv {$src} {$dest}");

I also tried this

$randie = '1548863958';
$src = "/var/www/forms_farm/storage/app/public/qrf/{$randie}";
$dest = "/var/www/file_store/qrf/{$randie}";

$file = new Filesystem();
$check = $file->copyDirectory($src.$randie, $dest.$randie);
23 Jan
5 months ago

jgravois left a reply on Vue.js & Jwt-auth With Missing Boundary

That was it. you === genius, me === idiot. Thanks!

jgravois left a reply on Vue.js & Jwt-auth With Missing Boundary

and before trying either of these I tried removing the header from the axios post and I got error: "Unauthorized" despite passing valid credentials (the same that works in insomnia)

jgravois left a reply on Vue.js & Jwt-auth With Missing Boundary

I ALSO tried this

login: function() {
                this.$store.dispatch('login', {
                    username: this.username,
                    password: this.password
                })
                .then()
                .catch(err => console.log(err))
            }
                    

and

export const login = (context, credentials) => {
    let formData = new FormData();
    formData.append('username', credentials.username);
    formData.append('password', credentials.password);

    axios.post('api/login', formData, {
        headers: {'Content-Type': 'multipart/form-data'},
    })
        .then(rsp => {
            console.log('LOGIN', rsp);
            //context.commit('ADD_TODO', response.data)
        })
        .catch(error => {
            console.log(error)
        })
};

stil same

jgravois left a reply on Vue.js & Jwt-auth With Missing Boundary

here's my new Vue method

login: function() {
                let formData = new FormData();
                formData.append('username', this.username);
                formData.append('password', this.password);

                this.$store.dispatch('login', formData)
                .then()
                .catch(err => console.log(err))
            }

and the new action

export const login = (context, credentials) => {
    axios.post('api/login', credentials, {
        headers: {'Content-Type': 'multipart/form-data'},
    })
        .then(rsp => {
            console.log('LOGIN', rsp);
            //context.commit('ADD_TODO', response.data)
        })
        .catch(error => {
            console.log(error)
        })
};

It is still "error: "Unauthorized""

Was that not what you meant?

jgravois started a new conversation Vue.js & Jwt-auth With Missing Boundary

I can use my login method to authenticate with Postman and Insomnia. However, when I try it with Vuex in a PWA, I receive the message

Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0 {"error":"Unauthorized"}

This is my login method

public function login(Request $request) {
        $credentials = $request->only(['email', 'password']);

        try
           {
               if(!$token = JWTAuth::attempt($credentials)) {
                   return response()->json(['error' => 'Unauthorized'], 401);
               } // end if
           } 
        catch(JWTException $e)
           {
               return response()->json(['error' => 'Could not create token'], 500);
           } // End try...catch

        return $this->respondsWithToken($token);
    } // end function

And this is my Vuex action

export const login = (context, credentials) => {
    axios.post('api/login', {
        username: credentials.username,
        password: credentials.password
    }, {
        headers: {'Content-Type': 'multipart/form-data;'},
    })
        .then(rsp => {
            console.log('LOGIN', rsp);
        })
        .catch(error => {
            console.log(error)
        })
};

When I post credentials to that endpoint in Insomnia, I get the response

{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvYmVhY29uLmRldlwvYXBpXC9sb2dpbiIsImlhdCI6MTU0O123A567NiwiZXhwIjoxNTQ5NDQ4OTg2LCJuYmYiOjE1NDgyMzkzODYsImp0aSI6IjhVNDJHWndVMWtHbWVzSkUiLCJzdWIiOjEsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.KeGFiAoddim8p1YNKv5vO09H2ZIKa2RZp8Z1yXWqILk",
  "token_type": "bearer"
}
20 Dec
6 months ago

jgravois started a new conversation Multiple Email Attachments & "Unable To Open File For Reading"

I have dynamically generated a .pdf from a Laravel view and placed it in the storage along with ZERO or more images.

I am trying to write a Mailer that will attach any and all files in the folder.

Currently the first files blows the app (but the email IS sent) with the Unable to open file for reading Swift_IoException.

The email shows the first file with a "downloading" message beneath.

The mailer looks like this:

public function build()
    {
        $report = QrfFormsSubmit::where('randie', $this->randie)->first();
        $images = [];
        $files = Storage::disk('public')->files("/qrf/{$this->randie}");

        $email = $this->view('emails.quality_present', $report->toArray())
            ->subject($report['employee'] . ' Quality Action Form Submission');

        foreach($files as $file) {
            $pops = explode('/', $file);

            $uri = collect($pops)->last();
            $email->attach(public_path() . '/' . $this->randie . '/' . $uri);
        } // end for

        return $email;
    }

jgravois started a new conversation Adding An Element To A Eloquent Collection

After creating a DB record, I need to add an additional element to the result before continuing.

I tried array_push but the exception was first element expected was an array and I gave it an object.

I tried ->put() bit the exception was there's no method put() in the model

I tried below and the error is Call to a member function getBindings() on array.

What do I do???

$newb = QrfFormsSubmit::create([
            'reporter' => request('sender'),
            'reporter_email' => request('sender_email'),
            'employee' => request('offender'),
            'employee_email' => request('offender_email'),
            'event_date' => request('event_date'),
            'event_time' => request('event_time'),
            'event_location' => request('event_location'),
            'notes' => request('description'),
            'description' => request('description'),
            'counter_measure' => request('counter_measure'),
            'initials' => request('initials'),
            'submitted_date' => Carbon::today('America/Chicago'),
            'form_id' => 3,
            'form_uri' => $filename
        ]);

        $location = Location::whereId(request('location_id'))->first();
        $formData = $newb->union(['location' => $location->location]);
09 Dec
6 months ago

jgravois started a new conversation Laravel-Passport & Laravel-Lighthouse

We recently lost our network admin and also have been requested by C-Suite to facilitate our front-end developers by moving to Grapql to allow them to slim our huge data objects.

My question is whether or not I should have a separate Laravel-Passport (Oauth) server apart from out data server (Laravel-Lighthouse) or can laugh and data be served from the same?

24 Nov
7 months ago

jgravois left a reply on Chunk Returns Empty Always

Boy, I was debugging the crap out of chunk() ... talk about the wrong place at the wrong time ... thanks!

jgravois started a new conversation Chunk Returns Empty Always

I absolutely NEED to use chunk to process a table of 120,389 records but no matter what article I find and try, if I use chunk(), I get an empty array. What am I doing wrong???

public function chunky()
    {
        $reporter = [];

        User::chunk(50, function ($users) {
            foreach ($users as $user) {
                $reporter[] = $user;
            }
        });

        return $reporter;
    } // end function
12 Nov
7 months ago

jgravois left a reply on Filtering And Reducing A Collection

@TYKUS - ->sum(component.value) gives me an undefined exception

jgravois left a reply on Filtering And Reducing A Collection

@TYKUS - all records are on the same order so the orderID should be the same

jgravois started a new conversation Filtering And Reducing A Collection

I have a collection with a nested object like below. I am trying to filter by the category and reduce the sum of value.

I have the filter part (I think) but don't know how the sum the values.

$value = ComponentsModel::with('component')
            ->where('model_id', $this->id)->get();

$cat1 = $value->filter(function($v) {
            return $v->component->cat == "1";
        });

Here's a sampling of the collection:

{
    id: 1,
    orderID: 7563,
    component: {
        id: 17,
        cat: "1",
        description: "actuator",
        value: 1250
    }
}.
{
    id: 2,
    orderID: 7563,
    component: {
        id: 452,
        cat: "QEC",
        description: "wire harness",
        value: 24
    }
},
{
    id:3,
    orderID: 7563,
    component: {
        id: 121,
        cat: "1",
        description: "thruster cowl",
        value: 3500
    }
},
{
    id: 4,
    orderID: 7563,
    component: {
        id: 502,
        cat: "QEC",
        description: "connector assy",
        value: 9
    }
},
{
    id: 5,
    orderID: 7563,
    component: {
        id: 87,
        cat: "1",
        description: "monitoring display",
        value: 500
    }
}
07 Nov
7 months ago

jgravois left a reply on A Comma In The Data Prevents A SQL Insert In Laravel

you were correct, of course

jgravois started a new conversation A Comma In The Data Prevents A SQL Insert In Laravel

I am importing an excel file into the database and some of the descriptions contain columns. This produces a Query Exception:

SQLSTATE[01000]: Warning: 1265 Data truncated for column 'ata' at row 1 (SQL: insert into zone_maps (description, part_number, cat, ata, master_zone_id, mfg_zone, adc_zone_1, qty_per_ac) values (VALVE, HYD RESERVOIR SHUTOFF, 0091520200-3, 3, 29-11-04, IF, RIGHT MAIN WHEEL WELL, 35, 1))

Is there another way to write this to protect the embedded comma?

ZoneMap::create([
        'description' => ($master ? $master->description : $row['description']),
        'part_number' => $pn,
        'cat' => ($master ? $master->cat : null),
        'ata' => ($master ? $master->ata : $row['ata']),
        'master_zone_id' => $row['zone_code'],
        'mfg_zone' => $row['mfg_zone'],
        'adc_zone_1' => $row['adc_zone_1'],
        'qty_per_ac' => $cnt
    ]);
20 Sep
9 months ago

jgravois started a new conversation Carbon/Carbon Is Kicking My Butt

I get a result like this when tapping into our ADP API for time off

[
  {
    "id": 1,
    "user_id": 1,
    "start_date": "2018-09-11 08:00:00",
    "end_date": "2018-09-20 12:00:00",
    "created_at": "2018-09-13 14:08:18",
    "updated_at": "2018-09-13 14:08:18"
  }
]

I need to determine on a regular basis the amount of work hours a staff has available for the CURRENT week. I am getting a return of 32 whereas I SHOULD be getting 12. Since he/she is on vacation Mon, Tues, Wed, and 1/2 of Thurs, he/she is available 4 hours on Thurs and 8 hours on Fri. I can't figure out WHERE the 32 is coming from.

public function staff_out()
    {
        $staffId = 1;

        $today = Carbon::today();
        $todayOpen = $today->copy()->addHours(8);
        $todayClose = $today->copy()->addHours(17);

        $mon = $today->copy()->startOfWeek(Carbon::MONDAY);
        $tues = $mon->copy()->addDays(1);
        $wed = $mon->copy()->addDays(2);
        $thurs = $mon->copy()->addDays(3);
        $fri = $mon->copy()->addDays(4);
        $sat = $mon->copy()->addDays(5);

        //return $off;
        $daysOfWeek = [
            'mon' => $mon,
            'tues' => $tues,
            'wed' => $wed,
            'thurs' => $thurs,
            'fri' => $fri,
            'sat' => $sat
        ];

        $hours = 0;

        foreach ($daysOfWeek as $day) {
            $result = StaffTimeOff::where('user_id', $staffId)->where('start_date', '<=', $day)->where('end_date', '>=', $day)->get();

            if($result->isEmpty()) {
                $hours +=  8;
            } else {
                $startDate = $result[0]->start_date;
                $endDate = $result[0]->end_date;

                if($today->startOfDay() == $startDate->copy()->startOfDay()) {
                    if((int)$startDate->format('G') >= 12 ) {
                        $hoursOff = 4;
                    } else {
                        $hoursOff = 0;
                    }
                } elseif($today == $endDate->copy()->startOfDay()) {
                    if((int)$endDate->format('G') >= 12 ) {
                        $hoursOff = 4;
                    } else {
                        $hoursOff = 0;
                    }
                } else {
                    $hoursOff = 0;
                }
                $hours += $hoursOff;
            } // end if
        } // end foreach
        
        return $hours;
    } // end function

ANY help is appreciated!!!

19 Sep
9 months ago

jgravois started a new conversation HasManyThrough Confustion

Table 1 - workscope [id, description, location_id] Table 2 - workscope_phases [id, phase_id, workscope_id, is_completed] Table 3 - tasks [id, workscope_id, phase_id, user_id, description, is_completed]

I have a distant relationship in that A WORKSCOPE_PHASE HAS MANY TASKS IN A WORKSCOPE

I am trying to eager load the phase|tasks via the workscope so I am trying a hasManyThrough relationship on the WorkscopePhase model.

public function tasks()
    {
        //A PHASE HAS MANY TASKS IN A WORKSCOPE
       return $this->hasManyThrough(Task::class, Workscope::class, 'id', 'workscope_id', 'phase_id', 'phase_id' );
    } // end function

I am getting

Unknown column 'workscopes.phase_id' in 'on clause' (SQL: select `tasks`.*, `workscopes`.`id` from `tasks` inner join `workscopes` on `workscopes`.`phase_id` = `tasks`.`phase_id` where `workscopes`.`id` in (3))

The definition of hasManyThrough is where I am confused

public function hasManyThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null, $secondLocalKey = null)
    {
        $through = new $through;

        $firstKey = $firstKey ?: $this->getForeignKey();

        $secondKey = $secondKey ?: $through->getForeignKey();

        return $this->newHasManyThrough(
            $this->newRelatedInstance($related)->newQuery(), $this, $through,
            $firstKey, $secondKey, $localKey ?: $this->getKeyName(),
            $secondLocalKey ?: $through->getKeyName()
        );
    }

$firstKey looks like the foreign key for the workscope_phases TO workscope relationship $secondKey looks this the foreign key for the workscope_phases TO task relationship

hence, I am lost

Any clarification is GREATLY appreciated!

26 Aug
10 months ago

jgravois left a reply on Looping Through An Array Without Knowing Keys

yeah, this isn't worth the time ... there is a nice vue.js package and the possibility of also setting up a node.js API ... I was just trying to do it on the backend because for some collections I am dealing with 615K+ records and if it was on the backend, I could pass it to an Artisan Command and not tie up the app for so long ... THANKS FOR THE TIME!!!

jgravois left a reply on Looping Through An Array Without Knowing Keys

@Cronix, Firebase just has NO love for PHP ... that gives me this ...

[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]

jgravois left a reply on Looping Through An Array Without Knowing Keys

@Cronix that gives me "Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR) Call to undefined method Google\Cloud\Firestore\DocumentSnapshot::toArray()"

@jeanpaul there isn't a set number of records ... in javascript I would do something like this but don't know what in PHP

Object.keys(experienceObject).map(e => {
    console.log(`key= ${e} value = ${experienceObject[e]}`)
});
25 Aug
10 months ago

jgravois started a new conversation Looping Through An Array Without Knowing Keys

I am trying to build a dynamic presenter to read and write to a Firestore database.

I have the post method pretty compact and concise and trying to refactor the get method and add flexibility to it as well.

However I don't know how to "read the keys" of an array ... meaning the code below works for the users collection because I know the fields firstname, lastname, name and email exist.

Is there a way to just loop through everything in the array without knowing the names of the columns?

<?php

namespace App\Presenters;

use Google\Cloud\Firestore\FirestoreClient;

class FirestorePresenter extends Presenter
{
    protected $client;

    public function __construct()
    {
        $this->client = new FirestoreClient();
    }

    public function getFireCollection($collection)
    {
        $reporter = [];
        $collection = $this->client->collection($collection);
        //$query = $collection->where('lastname', '=', 'Gravois');
        //$snapshot = $query->documents();
        $snapshot = $collection->documents();

        foreach ($snapshot as $document) {
            $reporter[] = [
                'User' => $document->id(),
                'First' => $document['firstname'],
                'Last' => $document['lastname'],
                'Email' => $document['email']
            ];
        } // end foreach

        return $reporter;

    } // end function

    public function postFire($collection, $object_unique_id, $data)
    {
        $collection = $this->client->collection($collection);

        $collection->document($object_unique_id)->set($data);
    } // end function
} // end class

09 Aug
10 months ago

jgravois left a reply on Using Dynamic Field Names In A Request

seems like a subtle difference but works well. Thank you!

jgravois started a new conversation Using Dynamic Field Names In A Request

I am posting this to the server:

db_fld: "notification_coo_aircraft_arrival"
deal_id: 1
label: "Notify head of operations of oncoming aircraft"
sort_order: 2
val: "uploaded"

Here is what I thought would be by controller method:

public function document_toggle($id)
    {
        $doc = DealDoc::where('deal_id', $id)->first();

        $doc->request('db_fld') = request('val');
        $doc->save();

        return response()->json(['msg' => $doc], 200);
    } // end function

The "$doc->request('db_fld') = request('val');" generates a "Expression is not assignable: Method reference" message.

Is there a way to use a posted string to identify the database field to save to?

Thanks in Advance!

06 Aug
10 months ago

jgravois left a reply on Using Chunk() Properly

understood ... thank you for your efforts and I will strive to ask better questions in the future

jgravois left a reply on Using Chunk() Properly

Funny, everyone ELSE says to reduce the amount of code to the minimum to repeat the error or issue ...

jgravois left a reply on Using Chunk() Properly

absolutely agree ... the return $reporter[] was just for me to see the dataset.

The actual function is

public function all_users()
    {
        User::chunk(50, function($users) use (&$reporter)  {
            $users->each(function($user) use (&$reporter)  {
                $user->updateFirebase();
                $user->updateRoster();
                $user->processKPIs();
            });
        });
        
        return response()->json(['msg' => 'Users Updated'], 200);
    } // end function

jgravois left a reply on Using Chunk() Properly

@Snapey Thanks for the reply!!! I simplified the example to get it working but I need to use chunk() because I am processing 45K records.

jgravois started a new conversation Using Chunk() Properly

I am trying to prevent out of memory issues with the following but I am returning NOTHING.

The commented out return User::all(); works fine. The dd() also shows 50 users.

public function all_users()
    {
        //return User::all();
        $reporter = [];
        User::chunk(50, function($users) {
            //dd($users);
            $users->each(function($user) {
                $reporter[] = [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email
                ];
            });
        });

        return $reporter;
    } // end function

Where have I gone wrong???

10 Jul
11 months ago

jgravois started a new conversation Trying To Save "false" Into A TinyInt

The GUI returns the string "true" or "false" for the Variance field. I have a controller method that is flexible enough to handle any value update by passing along the name of the column --

public function field_update(Request $request, $id)
    {
        if($request->input('column') === 'variance') {
            $request->merge(['newV' => !!$request->input('newV')]);
        } // end if

        $master = EcoComponentMaster::with('modeler')
            ->whereId($id)
            ->first();
        $master[$request->input('column')] = $request->input('newV');
        $master->save();

        return response()->json(['msg' => 'Updated'], 200);
    } // end function

However, that triggers a status code of 500

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'false' for column 'variance' at row 1 (SQL: update eco_component_masters set variance = false, updated_at = 2018-07-10 16:28:51 where id = 6553)

How can I fix this?

07 Jul
11 months ago

jgravois started a new conversation Vue 2: Can't Assign Prop

I have a global component in a Laravel application that is being passed the id of a model (not as in MVC) as a prop. I am assigning it to a local variable in the created hook and just trying to display it. I am also displaying the id from the Laravel controller in the blade file for reference. I see the Laravel id and the button but not the local variable. Am I understanding Vue.js incorrectly???

laravel controller:

public function model($id)
        {
            $model = AdcModel::whereId($id)->first();
            
            return view('model', compact('model'));
        } // end function

blade file:

@section('content')
        <div class="padded__container" style="margin-top: 60px;">
            {{$model->id}}
            <model-view
                    :current_user="{{$current_user}}"
                    :modelID="{{$model->id}}"></model-view>
        </div>
    @endsection

and component

<template>
        <span>
            <a class="button is-success" href="/modeler">Back</a>
            {{current_model_id}}
        </span>
    </template>
    
    <script type="text/babel">
        export default {
            data() {
                return {
                    current_model_id: null
                };
            },
            created() {
                this.current_model_id = this.modelID;
            },
        props: ['modelID']
    };
</script>

<style scoped></style>
26 Jun
1 year ago

jgravois started a new conversation API Resources -- Helper Methods

I have an API Resource (this is abbreviated for brevity) and I need to do some calculating so I added two helper methods. I first tried to call $this->getEstimatedCompletionDate() without passing through the Request thinking the $this was global throughout the class. Now I am trying with a passed in request and using both arrow and bracket syntax but both are returning null seemingly regardless of what I do.

Any ideas???

public function toArray($request)
    {
        //return parent::toArray($request);
        return [
             'avatar' => optional($this->air_class)->avatar,
            'estimated_completion_date' =>  $this->getEstimatedCompletionDate($request),
            'expected_completion_date' =>  $this->getExpectedCompletionDate($request),
            'expected_days_to_complete' => $this->goals[$this->workscope_package],
            'id' =>  $this->id,
        'phases' =>  WorkscopePhasesResource::collection($this->whenLoaded('phases')),
        ];
    }

    public function getEstimatedCompletionDate($ws)
    {
        return $ws->estimated_completion_date;
    } // end function

    public function getExpectedCompletionDate($ws)
    {
        return $ws['expected_completion_date'];
    } // end function
16 Jun
1 year ago
06 Jun
1 year ago

jgravois started a new conversation API Resource Not Passed To Method

I have an eloquent call and pass the results through a Resource:: which I still call transformers

$ws = Workscope::with('apu', 'conditionals', 'dis_locate', 'docs', 'engines', 'project', 'tasks', 'ws_color')
            ->whereId($id)
            ->first();
$scope = new WorkscopeTransformer($ws);

If I return $ws, I get the original request with all 310 datapoints.

If I return $scope, I get my transformed request with the 28 datapoints that I need.

All good ... (it seems)

if instead I run

if($scope['conditionals']->schedule_engines) {
            $eTasks = MasterTask::engines_tasks($scope, $sortCounter);
            $sortCounter += $eTasks['total_tasks'];
            $reporter['engines'] = $eTasks;
        } // end if

and I dump&die $scope in MasterTask::engines_task, I get the original request with all 310 datapoints.

Am I misusing the Resource? I can supply dumps or any other code required but I kept it to this at first for brevity.

Thanks in advance!

27 May
1 year ago

jgravois started a new conversation Laravel-Modules -- Importing Class?

I installed the promising package Laravel-Modules and added a routes/web/workscopes.php routes file. Is there a way to "import" the path rather than having to type out the following each time:

<?php

Route::prefix('workscopes')->group(function() {
    Route::get('about', '\Modules\Workscopes\Http\Controllers\[email protected]');
});
21 May
1 year ago

jgravois left a reply on Update Fails And I Can't See Why

OMG ... it wasn't ... THANKS!!!!!!!!!!!!!!

jgravois started a new conversation Update Fails And I Can't See Why

We have vehicles that can be reserved. The reservation is APPROVED before hand and I am trying to update the reservation to IN-USE on the recall of the records. The parent record (the Vehicle) updates as instructed but the record itself WILL NOT UPDATE.

Is there ANYTHING in the code below that I am doing wrong and can't see?

$inUse = VehicleReservation::where('sign_out', '>=', Carbon::today()->startOfDay())
            ->where('status', 'approved')->where('was_returned', false)->get();
        return $inUse[0];

        if($inUse) {
            foreach($inUse as $v) {
                $v->vehicle->update(['status' => 'in-use']);
                $v->update(['status' => 'in-use']);
            } // end foreach
        } // end if