Roni

Experience

52,380

4 Best Reply Awards

  • Member Since 3 Years Ago
  • 636 Lessons Completed
  • 14 Favorites

16th May, 2018

Roni left a reply on Throwing Exceptions Vs Returning Response • 1 week ago

@skliche I know it's 2 years later. I just somehow needed to read "extend the class and override the method". It's been a 10 hour day and my brain just wasn't going there on it's own. :)

cheers !

10th May, 2018

Roni started a new conversation Is There A Check To Skip A Specific Migration For Unit Tests In A Migration Class? • 2 weeks ago

For example

 public function up()
    {
        If ( ! <test indicator>){
            // migrate stuff here
        }
    } 


Roni left a reply on Auth()->id() Returns Null In Static Trait Boot Function • 2 weeks ago

1 million dd()'s later it's the seed migration that throws off allt he tests ! ouch! dang it vue for making me need to re-seed!

Roni started a new conversation Auth()->id() Returns Null In Static Trait Boot Function • 2 weeks ago

Hi, I finally got around to the laravel Forum TDD series, which is a great primer. At some point, auth()->id() stopped working in a trait boot function, and started returning null instead of the authorized user.

I'm using php 7.2.2, and laravel 5.4.15

her is the triat right out of the course, and I'm positive it worked at some point.


trait RecordsActivity
{
    /**
     * Boot the trait.
     */
    protected static function bootRecordsActivity()
    {
        if (auth()->guest()) return; //This returns true instead of false which forces an early return.

        foreach (static::getActivitiesToRecord() as $event) {
            static::$event(function ($model) use ($event) {
                $model->recordActivity($event);
            });
        }

        static::deleting(function ($model) {
            $model->activity()->delete();
        });
    }


here is the ActivityTest Class that calls it, again right out of the repo.


?php

namespace Tests\Feature;

use App\Activity;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;

class ActivityTest extends TestCase
{
    use DatabaseMigrations;

    /** @test */
    public function it_records_activity_when_a_thread_is_created()
    {
        $this->signIn();

        $thread = create('App\Thread');

        $this->assertDatabaseHas('activities', [
            'type' => 'created_thread',
            'user_id' => auth()->id(),
            'subject_id' => $thread->id,
            'subject_type' => 'App\Thread'
        ]);

        $activity = Activity::first();

        $this->assertEquals($activity->subject->id, $thread->id);
    }

    /** @test */
    function it_records_activity_when_a_reply_is_created()
    {
        $this->signIn(); 

// if you add dd(auth()->id()) at any point other than the boot method it returns an id

        $reply = create('App\Reply');

        $this->assertEquals(2, Activity::count());
    }

    /** @test */
    function it_fetches_a_feed_for_any_user()
    {
        $this->signIn();

        create('App\Thread', ['user_id' => auth()->id()], 2);

        auth()->user()->activity()->first()->update(['created_at' => Carbon::now()->subWeek()]);

        $feed = Activity::feed(auth()->user(), 50);

        $this->assertTrue($feed->keys()->contains(
            Carbon::now()->format('Y-m-d')
        ));

        $this->assertTrue($feed->keys()->contains(
            Carbon::now()->subWeek()->format('Y-m-d')
        ));
    }
}



Thanks, any advice would be greatly appreciated.

9th May, 2018

Roni left a reply on Refused To Execute Script From ''<js File> Because Its MIME Type ('text/html') Is Not Executable, And Strict MIME Type Checking Is Enabled. • 2 weeks ago

Hi nate, sorry I haven't looked at that repo in about 8 months, but i can either sneak late tonight or on the weekend after the jets game (go winnipeg)!

18th January, 2018

Roni left a reply on Sort A Collection By A Relationship Value • 4 months ago

Shazam! @jbloomstrom, nice! It just worked! I have to take it apart and see why but thanks. I never thought of transform. @kreierson, I'm not sure I want that in all situations, I've never tried ordering a relationship in that fashion, but I'll try some tests next week and see if it holds. Thank you as well.

Roni left a reply on Sort A Collection By A Relationship Value • 4 months ago

@jbloomstrom, Diving in a little deeper to eloquent, it looks like laravel active record won't work in this way, when it's gathering the records from a relationship, it does a


select from orders (outer object) where exists (then some inner logic)

It then it applies your group by and order offset and limit to the outer loop. So regardless of you inner return order it makes no difference because it's only a boolean existential, connection.

I'm not saying there isn't a way with eloquent, but I don't know it. But you'll need to render a join and cleanup of some sort to have any effect. Hence the reason I was hoping to deal with it at the collection level. Where's @adamwathan when you need him :)

Roni left a reply on Sort A Collection By A Relationship Value • 4 months ago

Another clarification, I can't just use $touches on the order contact note to the relationship, as lots of things update an actual order, so the ordering would be come random as different people go about their tasks.

Roni left a reply on Sort A Collection By A Relationship Value • 4 months ago

@jbloomstrom, I see what you are saying, I'm getting the data, just out of order, but I can't sort in on the collection. or from the DB. let me explain a bit further, to clarify what I'm trying to accomplish.

Basically, I'm using eloquent to get the active model approach, where instead of getting a DB record 1:1 tuple approach of getting the order notes, and then programatically grouping them into orders and displaying them, I'm grabbing the orders with their respective notes, and then displaying the order some basic order information, and then a list of it's notes followed by a place to add a new note.

This way the managers can always see what orders are being worked on and add their own notes. It keeps actively processed orders on the top of their visual interface. Like a facebook post where as people add a comment, the post rises to the top of a timeline, however the comments still stay in chronological order with the earliest on the top and the newest on the bottom.

However, what I'm getting, depending on the collection sort method I use, is sorting by any value specifically on the order, like order->updated_at or order->id. But if I want to sort the orders based on the max created_at value (descending) of the orderContactNote object when it's available, (when it's not available clearly kick it to the bottom of the list). So that if you have a contact with a client and note it, that Order object, bubbles to the top of the page.

The sortByDesc() in the docs leads me to believe it would do the job, but it doesn't seem to be handling it.

Roni left a reply on Sort A Collection By A Relationship Value • 4 months ago

Thanks @bashy, thats helpful, I never checked when before, however it doesn't impact the sorting. But I appreciate the refactor.

Roni started a new conversation Sort A Collection By A Relationship Value • 4 months ago

I have a model Orders, which has a relationship


public function orderContactNotes()
    {
        return $this->hasMany('App\OrderContactNote');
    }


Now Orders get updated all the time, and contact notes as well. I have a view where the requirements need to show orders based on the most recent note. Orders may have many notes.

I thought this would have been simple, but I think I'm missing something in eloquent or the collection sorting

I've tried a number of possibilities both by them selves and in tandem here are some options that don't seem to work

public static function notesByStaffExcept($staff_id, $limit=100, $id=null)
    {
        $list =  self::with(
            [
                'orderContactNotes',
                'orderContactNotes.staff',
                'orderContactNotes.noteType',
                'user'
            ]
        )
            ->whereHas('orderContactNotes', function($query) use($staff_id) {
                return $query->where('staff_id','<>',$staff_id)->orderBy('updated_at','desc');
            });

        if(!is_null($id)){
            $list = $list->where('id', $id);
        }
        return $list->limit($limit)->get()->sortByDesc(function ($order,$key){
            return optional($order->orderContactNote)->'created_at';
        })->values();
    }

OR adding a max although I think the scope of the max() is the issue.


public static function notesByStaffExcept($staff_id, $limit=100, $id=null)
    {
        $list =  self::with(
            [
                'orderContactNotes',
                'orderContactNotes.staff',
                'orderContactNotes.noteType',
                'user'
            ]
        )
            ->whereHas('orderContactNotes', function($query) use($staff_id) {
                return $query->where('staff_id','<>',$staff_id)->orderBy('updated_at','desc');
            });

        if(!is_null($id)){
            $list = $list->where('id', $id);
        }
        return $list->limit($limit)->get()->sortByDesc(function ($order,$key){
            return optional($order->orderContactNote)->max('created_at');
        })->values();
    }


Any clarification would appreciated.

8th January, 2018

Roni left a reply on Running Headless Chrome On Vagrant Homestead Using Php Shell_exec • 4 months ago

any solution?

Roni left a reply on Phpstorm Command Line Hack • 4 months ago

Thanks @bobbybouwmann, I'll give that a try. Maybe someone has some secret sauce they can share with us.

Roni started a new conversation Phpstorm Command Line Hack • 4 months ago

Just a whim, but does anyone know how to open a file in phpstorm when the ide is already running?

For example, if the ide is closed. From the terminal (iterm2 on macOS high sierra) I can simply write pstorm <path/to/file> much like the sublime text subl <path/to/file>. However, if the ide is running, this command has no effect.

It's just a pet peeve making a migration or controller then navigating to it and syncing the directory (sometimes it takes a minute to auto detect and command + P wont work unless it's indexed) I'd love to add that to my artisan aliases.

18th December, 2017

Roni left a reply on Adding A Data Element Thats Observable. Vue/Axios • 5 months ago

Hi @SyedAbuthahir, thanks, thats actually where both option 2 and 3 are from. I'm still not a JS guru, so I'm sure I'm missing something there, but I think if this was an easy fix someone would have thrown something out, so for posterity's sake, here is the solution I utilized.

Again, many of the solutions I come to come out of a need to not spend more than a half day working on a problem. It's just to expensive and hampers work flow. So my cheat solution was to change my endpoint, and run the data through a php controller sanitizing function.

In php I just created a notes array as an empty array in each collection object. Then returned the sanitized dataset to the original vue problem. Once the notes array was there, there was no need for me to do any further reactive toying around because the array was now reactive.

This won't solve your problem if you can't manipulate endpoints in a project, or you are working in a situation where you are required to solve this in vue, but if you can just deal with it in php beforehand. It's quick and dirt easy.

here is the code $list was the original value, I extracted the notes, and simple made an empty notes collection in each list item, and then populated the notes into that element when it existed.

* Don't use null, it won't render in a vue list v-for directive. * Don't forget to use collection->values() to reset the indices of the to 0,1,2 ... or JS won't consider it a proper array, (that cost me 30 min too)

$col = collect($list)->keyBy('id');

$col->each(function($order) use ($notes){

    $order->notes = collect();

    if($notes->has($order->id)) {
        $order->notes->push($notes->get($order->id));
    }
});

$col = $col->values();

15th December, 2017

Roni started a new conversation Adding A Data Element Thats Observable. • 5 months ago

I have a data element rendering a list. From an axios request. It's getting it's data from a database Query with a collection. In some cases the collection has another notes collection element, in others where there are no notes, there is no notes collection added.


Object 1 > stuff
Object 1 >notes > array[0] > "Lorem"
Object 1 >notes > array[1] > "Ipsum"

Object 2>stuff

Object 3 > stuff
Object 3 >notes > array[0] > "sit"


The all render perfectly on a app with a report. However, if I need to add a note, when I add it via axios.patch on object 1 or object 3 and then push the new data item to the object.notes array, it works perfectly.

However when I need to create the notes array and then add it in object 2, it adds, but it's not reactive and won't get re-rendered.

I've tried several methods of making it observable but I haven;'t been able to figure this one out. Here are some of the code options I've tried.


//there is a tableData: [] in the data section
//this computed section allows a filter on the tableData. I don't think it's relevant but just in case.

computed: {
        filteredData() {

            return this.tableData.filter(row => {
                // console.log(this.searchKey.toLowerCase());
                // console.log(row.user.first_name);

                return row.name.toLowerCase().indexOf(this.search.toLowerCase()) > -1

            });

        },

}, 

//When I update the form this function is triggered:

postNote(item, order){
    console.log(item,order);
    axios.get('/api/v1/phonelist/note/create',{
        params: {
            api_token: this.api_token,
            staff_id: this.api_user,
            order_id: order,
            note_type_id: this.newNoteType[order],
            note: this.comment[order],
        }
    }).then((response) => {
        console.log(response.data);

    //OPTION 1 this works for data that already has a notes array and new notes are added

     this.tableData[item].notes.push(response.data.pop());

    //OPTION 2: Looking at the deeper reactivity section from the vue docs I tried this.
    //the data looks perfect on the vue developer tool, but it's not re-rendering.

        if(this.tableData[item].notes == null){
            this.filteredData[item] = Object.assign({},this.tableData[item],{notes: response.data})
            // Vue.set(this.tableData[item].notes,0,response.data.pop());
        }else{
            this.tableData[item].notes.push(response.data.pop());
        }

    //OPTION 3
    //Data also looks perfect but again it won't re-render.

    if(this.tableData[item].notes == null){
            this.tableData[item].notes = [];
            Vue.set(this.tableData[item].notes,0,response.data.pop());
        } else{
            this.tableData[item].notes.push(response.data.pop());
        }

        //clean up props
        this.newNoteType[order] = undefined;
        this.comment[order] = undefined;

    }).catch((errors) => {
        console.log(errors);
    });

    //end with

},

in case this helps here is the view layer where the note is rendered

      <article class="media" v-for="(note,index) in props.row.notes">
            <figure class="media-left">
                <p class="image is-64x64">
                    <img :src="getStaffAvatar(note.staff_id)">
                </p>
            </figure>
            <div class="media-content">
                <div class="content">
                    <p>
                        <strong>@{{ note.name }} @{{ note.staff_id }}</strong>
                        <small>@{{ Date.create(note.created_at).relative() }}</small><br>
                        <strong>@{{ note.description }}</strong>
                        <p v-if="note.note !== null">@{{ note.note }}</p>
                    </p>
                </div>
            </div>
        </article>


Any ideas or solutions welcome, if more code is needed please advise.

Roni left a reply on Is It Worth Javascriptifying The Front-end? • 5 months ago

I haven't watched the series and it definitely adds a layer of complexity, however, in some cases especially a forum like scenario where you may have several layers deep of responses and other responses that are not related, screen refreshes and full reloading often result in distractions. Especially when you are not in control of all the design where you can mitigate those.

I'm feeling the pain of vue as it's not nearly as easy as blade for me ... yet. However, it definitely has a place where re-rendering is even a minor distraction. Try not to think of it as a programmer but rather as a user, who may have to spend several hours a day on your app.

If you can save them small distractions and annoyances that add up to 100x a day, and possibly across 10-100 employees, the extra pains you take pay massive dividends.

29th November, 2017

Roni left a reply on Anyone Know A Way To Get Dd($something) Nicely Formatted In The Network Preview Tab Of Google Chrome? • 5 months ago

Thanks, that did clean it up a bit. Much appreciated.

Roni left a reply on Anyone Know A Way To Get Dd($something) Nicely Formatted In The Network Preview Tab Of Google Chrome? • 5 months ago

Thanks @ejdelmonico, I'm getting the same thing as the dd with that one.

This isn't the worst: dd(print_r($request->all()));

For now, I'm just trying to use it to make sure my requests are sending in the right data and at certain points where Vue is receiving data. It's been a while, but in the back of my head it used to just work.

Again this is only in the network pane of the devtools. In the regular window of chrome 62 it all returns as expected.

Roni started a new conversation Anyone Know A Way To Get Dd($something) Nicely Formatted In The Network Preview Tab Of Google Chrome? • 5 months ago

Been working on a fair amount of vue lately, as as I dd() a few things, in the preview tab I end up with stuff like this:

Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0

23rd November, 2017

Roni started a new conversation Relationship Create Not Working As Expected. • 6 months ago

I'm working on a laravel 5.5 application, and after debugging for an hour I've stumbled across the following issue when building up an object. I can't for the life of me figure this one out, so if someone could point me at why this is happening that would be awesome.

model


    protected $guarded = [];
    //not a mass assignment issue

    /**
     * Get the compression profile record associated with the User.
     */
    public function compressionProfile()
    {
        return $this->hasOne('App\CompressionProfile');
    }

    /**
     * Get the family that owns the User.
     */
    public function family()
    {
        return $this->belongsTo('App\Family');
    }

controller


//create a family for the user
            $user->family()->create([]);

            //create compression profile with first step for accidental redirection
            //and add the current compressionProfile onboarding version from env
            $user->compressionProfile()->create([
                'profile_redirect_to' => 'conference.profile.step.2',
                'current_profile_version' => env('APP_VERSION')
            ]);


Does the eloquent relationship builder create() only work on the hasOne model?

I ended up hacking out this:


$user->family_id = $user->family()->create([])->id

But it feels unclear. Thanks

22nd November, 2017

Roni started a new conversation Anyone Know How To Set Up Laravel Mix To Utilize Subdomains? • 6 months ago

I have a project where we have a section like admin.site.com, and I've been trying to figure out how to get laravel mix and browsersync to let me do something like admin.localhost or admin.domain.dev.

Any help would be appreciated.

10th November, 2017

Roni left a reply on Is There A Way To Make Private Images? • 6 months ago

Thanks @CJJ, I was about to check out digital ocean spaces for production, but I'm pretty sure the interface is identical. If you can throw up a code example, I'll switch over best answer to you.

Roni left a reply on Is There A Way To Make Private Images? • 6 months ago

Found this online, and it still works.

Move images that require interception and authentication/authorization or whatever guards you want into storage or any other path.

Then once it's out of public you can cane make a route to it, I chose "sigs" in my storage directory, you can choose anything:


Route::get('sigs/{filename}','[email protected]');

Then you can apply middleware on the route itself or in the controller, and finally, return the image


return response()->download(storage_path('/sigs/'.$filename), null, [], null);

now my secure image src is simply sigs/filename and it's secured with my guard of choice.

Cheers hope this helps someone.

Here is the link where I found the solution:

https://laravel.io/forum/04-23-2015-securing-filesimages

Roni left a reply on Is There A Way To Make Private Images? • 6 months ago

This doesn't work, it will intercept anything that is not a valid image and send you to authenticate. However, if you do get the actual file name it will just serve it and the middleware will never trigger :(

Roni started a new conversation Praetorian • 6 months ago

Is it just my pre-coffee delusional state or is there a little "pi" symbol on a button on the laracasts site in the bottom right corner!! Reminds me of an old movie "the net". Have we all been hacked!?!?!

Roni started a new conversation Is There A Way To Make Private Images? • 6 months ago

I'm looking at adding peoples signatures to an app during agreements or deliveries online, through any touch device. That's working fine. However right now, in our test phase the images are stored in the public directory which seems off.

Is there a way to store them privately, like in storage or assets, yet still show them in internal staff reports? Any time I point I seem to just get a blank image.

Alternatively can I put a guard on a public directory? for example Make a route


Route::get('/public/img/signatures/{slug}','[email protected]')->middleware('auth:staff');

then just return the image in the controller?

Any feedback appreciated.

1st November, 2017

Roni left a reply on Axios Without CSRF And Requested With Headers • 6 months ago

@theUnforgiven thanks also, I'm sure that method will work, I haven't attempted it yet, I don't know what the best practise is in these cases. I just saw the code snippet and it worked, so I committed and moved on. But I'll give it a try at some point when the pressure lets up. Cheers.

Roni left a reply on Axios Without CSRF And Requested With Headers • 6 months ago

Thanks for that, honestly I'm not sure and perhaps I'm misusing nomenclature. But I was using axios internally just for some easy for manipulation magic just to make the user interfaces a little more automatic for the users. Getting data as they respond to specific questions.

At some points I need to access API's externally, perhaps to get a list of JSON objects from a different service, both use cases used axios.get.

When I removed the headers the external just worked, however your solution allows me to do both.

I keep promising myself I'll dive into vue.js vanilla js and axios when time permits, instead of just backend work. It just seems like time never permits.

Thanks again. that was a life saver.

26th October, 2017

Roni started a new conversation Axios Without CSRF And Requested With Headers • 7 months ago

Hi,

Using Laravel 5.5 and vue (I'm weak at JS) I'm making some axios requests that run both internally and externally to other content. The internal content is fine and needs CSRF tokens to protect our system. However the same CSRF are applied to external calls.

is there a way to keep using window.axios for internal calls and some other instance of axios kept for external requests?

Right now to get the externals working i've commented out the following:

bootstrap.js

window.axios = require('axios');

// window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */
//
// let token = document.head.querySelector('meta[name="csrf-token"]');
//
// if (token) {
//     window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
// } else {
//     console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
// }


That solves all the external issues but removes protection on the system.

How can I make something like externalAxios to make external calls while keeping axios for internals?

Thanks in advance for your time.

25th October, 2017

Roni left a reply on Validation - Other Field Has Value • 7 months ago

@JoeDawson , thanks! I was facing a really ugly validating task, looking for some built in solution. Pointing out that it's just a damn array that can be manipulated was such an easy solution that somehow I just ran right by it.

Cheers a year later!

2nd August, 2017

Roni left a reply on Laravel Mix Stylus And Bulma • 9 months ago

Any help would be appreciated, the way I do it I can't use browsersync any more.

Here is an example of my webpack.mix.js


mix.stylus('resources/assets/stylus/front/landing.styl', __dirname + '/tmp/public/build/tmp/css/front/');

//other staging here

mix.copy(__dirname+ '/tmp/public/build/tmp/css/front/landing.css','resources/assets/css/landing.css');

// finish organizing files.

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css')
    .then(()=>{
        if (fs.existsSync(__dirname + '/public/build')){
            console.log('file exists');
            fs.removeSync(__dirname + '/public/build');
        }else{
            console.log('file doesn\'t exist');
        }
});

mix.browserSync({
    proxy: 'domain.dev'
});


when the promise returns to delete the directory with all the staging files if the watch option is on, it will just keep running in an infinite loop.

My earlier configs seemed to work but now, it seems mix.preprocess "forces" you to use your public directory, instead of allowing you to process stylus to a css file directly in your resource/assets. I can't seem to find a work around where, I can pull in all our stylus core, and still use bulma sass.

Any ideas welcome.

Roni started a new conversation Laravel Mix Stylus And Bulma • 9 months ago

Anyone ever use bulma, but program the overrides in stylus? I got used to stylus, and now I find myself maintaining two variables files and overrides.

I mix stylus down to CSS then import it into sass build so I can override bulma. Is there a better way?

18th July, 2017

Roni left a reply on Is There A Good Tutorial Regarding Pushing Laravel With Vue Components Into Production On Forge • 10 months ago

It wasn't that but you got my brain out of a 4 hour rut.

-Thank you

Roni left a reply on Is There A Good Tutorial Regarding Pushing Laravel With Vue Components Into Production On Forge • 10 months ago

Yes, and extracting them to a vendor library. referencing both manifest and vendor

Roni started a new conversation Is There A Good Tutorial Regarding Pushing Laravel With Vue Components Into Production On Forge • 10 months ago

I'm pretty new to vue.js, and I've started using it in conjunction with axios adding them to my laravel projects.

However, it seems that everything just works locally, but once you move to deployment to work there are a host webpack nightmares waiting out there. I use laravel forge, which I would have thought would be opinionated to work easily with webpack and vue, but it doesn't seem to be.

Are there any good tutorials that take you past development and into deployment? Anyone know the secret sauce of why everything that works perfectly locally may die a painful death in production.

Any advice welcome.

17th July, 2017

Roni left a reply on Refused To Execute Script From ''<js File> Because Its MIME Type ('text/html') Is Not Executable, And Strict MIME Type Checking Is Enabled. • 10 months ago

@jlrdw on the script tags in the component? I've tried application/javascript text/javascript I've torn apart and re-written the code in 20 ways. Always the same. And all of them work perfectly in local development.

I'll open a ticket on forge. Thanks though.

Roni left a reply on Refused To Execute Script From ''<js File> Because Its MIME Type ('text/html') Is Not Executable, And Strict MIME Type Checking Is Enabled. • 10 months ago

Nope, the forum just filtered out my place holder. I updated it for clarity. Thx for pointing out that it looked weird.

Roni started a new conversation Refused To Execute Script From ''<js File> Because Its MIME Type ('text/html') Is Not Executable, And Strict MIME Type Checking Is Enabled. • 10 months ago

I have a small Laravel app and I decided to add some vue.js and axios to it. At first I developed it all as one big file, but after going through the Object Oriented forms series on Vue 2, decided to get mix involved and make a series of components.

Locally it works great. just a few elements that perform updates in the background on change.

When I put it in production on a forge provisioned droplet I'm getting this error.

Refused to execute script from 'https:///js/admin/leadHandler.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. On line 1,

Line 1 is import Vue from 'vue'

I'm using vue and axios that are installed from NPM and compiled. prior to this I was using a CDN which did work. Again, it was all one file at that point. Here are the files.

leadHandler.js


import Vue from 'vue';
import axios from 'axios';
import Form from '../core/Form';

window.axios = axios;
window.Form = Form;
window.eventBus = new Vue();


import StatusSelect from '../components/StatusSelect.vue';
import ArchiveButton from '../components/ArchiveButton.vue';

new Vue({
    el:'#app',
    components: {
        ArchiveButton,
        StatusSelect

    },

    data:{

    },

    created(){
        axios.get('/admin/api/statuses')
            .then(res=>{
                eventBus.$emit('initSelect', res.data);
            })
            .catch(error=>console.log(error.response)
            );
    },

    methods:{
        onSubmit(){
            this.form.post('/admin/lead/archive')
                .then(response=>{})
                .catch(error=>{})
        }


    }
});
 

SelectStatus.vue


<template>
    <select name="status" v-model="status" @change="changed()" class="form-control input-lg btn-primary">
        <option v-for="(option,id) in options" v-bind:value="option.id">{{option.name}}</option>
    </select>
</template>
<script>

    export default{
        props: {
            leadId: {
                type: Number,
                required: true
            },
            existingStatus: {
                type: Number,
                default: 1
            }
        },
        data() {
            return {
                status: this.existingStatus,
                statusUpdated: false,
                options: [
                    // {key: 1, value: 'New Lead'},
                    // {key: 2, value: 'Reactivated'},
                    // {key: 3, value: 'In Progress'},
                    // {key: 4, value: 'Converted'},
                    // {key: 5, value: 'Lost'}
                ]
            }
        },
        created(){
            this.retrieveStatuses();
        },
        methods: {
            changed: function () {
                console.log('internal changed' + this.status);

                axios.post('/admin/lead/update-status/',
                    {
                        lead: this.leadId,
                        status: this.status,
                    }
                )
                    .then(response => {
                        this.statusUpdated = true;
                        // console.log(response);
                        Event.$emit('request', response);
                    }).catch(error => {
                    this.statusUpdated = true;
                    // console.log(error);
                    eventBus.$emit('request', error.response);
                });
            },
            retrieveStatuses(){
                eventBus.$on('initSelect', (value) => {
                    this.options = value
                });
            },
        }
    }
</script>

Thanks -Roni

11th July, 2017

Roni left a reply on Storing Data Shared Between Elements. • 10 months ago

Thanks again for the clarification got them both working. Is one way optimal? Less overhead?

10th July, 2017

Roni left a reply on Storing Data Shared Between Elements. • 10 months ago

@jaydeluca I haven't figured out the props solution, though the bus is working perfectly. if you have a moments to jot down the props or put a link to for posterity's sake that would be awesome.

Cheers and thx again

Roni left a reply on Storing Data Shared Between Elements. • 10 months ago

@jaydeluca

mind=>blown!

Thanks a million.

Roni left a reply on Storing Data Shared Between Elements. • 10 months ago

One sec, you aren't passing it, you are almost using an exception to handle that, so it bypasses the timing issue! Am I misreading? Emit => throw, and On is like a listen?

Roni left a reply on Storing Data Shared Between Elements. • 10 months ago

@jaydeluca,

Thanks jay, I've been experimenting with the bus, but I think it's a JS timing thing that I'm not aware of. Right now, the JS components and root instance are all in 1 file and the root vue instance is at the bottom per vuejs.org.

So it appears that when I try to reference it off the element, it's not instantiated yet. When I used the shared store it doesn't die like that it just seemed to not save.

I'm learning JS with Vue JS so scope resolution for JS and Vue is still a bit fuzzy for me.

Now I can move the created function to the root element, and populate the root data. But won't the vue components have already rendered by then?

Also why even bother with a shared state element if it can be so easily managed through the root element?

Sorry I know I'm running before walking, I just can't find the right tutorial to take me through the basics that relates to Vue yet.

Roni started a new conversation Storing Data Shared Between Elements. • 10 months ago

I'm super new to JS is general and specifically Vue. I have a series of formed using axios to get data from specific laravel API endpoints. This all works. However it's not optimized. I have a select box which is populated by a data endpoint query. But right now, it's getting populated in my created function on the component, and therefore if I have 100 components on the same page for a report, it's performing the same query 100X to initialize each select field.

What I'd like do do is check if the data has been fetched and saved once, and if so, just use that data for the rest of the elements. I'm not sure how to accomplish this in JS and more specifically in Vuejs 2.0

here is what I'm doing:

Data element of the component


data() {
        return {
        // some data for the element
    options: [
                // list of {key: <an id>, value: <some value>} from the db
            ]
        }

created function for the element

created(){

    this.retrieveStatuses()

}

//this is in methods

retrieveStatuses(){
            console.log(Event.formInit);
            if(Event.formInit.length > 0){
                this.options = Event.formInit;
            }else{
                axios.get('/admin/api/statuses')
                    .then(response=>{
                        console.log(response.data);
                        Event.formInit = response.data;
                        this.options = Event.formInit;
                    })
                    .catch(error=>console.log(error.response)
                )
            }
        },

There is a window.event Vue Object per laracasts vuejs lesson https://laracasts.com/series/learn-vue-2-step-by-step/episodes/13

I've added a data section to it with an array called formInit:[], I've also tried adding it on the root vue instance, but that is loaded after the element so it fails with an error.

No matter what happens outside the scope of the if statement Event.formInit never holds state, and therefore we always enter the else condition.

Thanks for any advice.

19th May, 2017

Roni left a reply on Polymorphic User Client Relationship • 1 year ago

Yeah, I've never used polymorphic relations before, but a client and client relaiton are so different in the database, they are used to represent totally different things and have different visualizations. However, an oddly non considered use case has come up where the client relation has become a client as well, and now there has to be some changes to adapt to the situation. So in fact a user can now be both, therefore have both relationships filled. Which views are defaulted etc... has all come into question.

This polymorphic feature seemed like it might fit the bill for a solution.

Roni started a new conversation Polymorphic User Client Relationship • 1 year ago

Hi, I'm trying to wrap my head around a polymorphic relationship to login to the a site.

The app has clients who may or may not have login credentials, yet we still track their data as "Clients". The the Client may have family / freind relationships defined in the system that will have logins. The only reason for the ClientRelation is the client is underage and is not able to hold an account. Therefore when we have a ClientRelation, it ALWAYS has login credentials.

Now the system takes users who can log in. A user may be a relation or the actual client. However this is a case where a user may be both a relation and a client for example both parent and child use the service, however parent still get the reported material for the underage client.

At first I had thought this would be a 1:1 relationship where a user would belongTo either a Client or a ClientRelation. Clients would have a nullable 1:1 relationship to user. And ClientRelation would have a 1:1 non-nullable relation to user.

Would the migrations be

User id --stuff userable_id userable_type

Client id --stuff

ClientRelation id --stuff

The models


//Client

public function user(){
    return $this->morphOne(User::class,'userable');
}

//ClientRelation
public function user(){
    return $this->morphOne(User::class,'userable');
}


Since I already know the class and the id of the linked object in the user object do I need to put a relationship there for it to pull the object? Is there a better way to deal with this or is a polymorphic relationship a sound solution for this instance?

18th May, 2017

Roni left a reply on Laravel/Tinker No Spaces • 1 year ago

Tried solving this on homebrew front as well, but in the end it was taking too much time, so I spent a late night doing a fresh install of macOS sierra, and homebrew, and problem was solved instantly. Quicker than giving it additional time.

9th May, 2017

Roni left a reply on Laravel/Tinker No Spaces • 1 year ago

@Cronix, thanks yeah I was thinking about it, but after converting to valet it's just so fast. can remember spending hours on "nfs" fixes, super waste of time since I have no admin type skills. I may just play on a staging droplet for a dollar. I rarely use tinker. Its just, for testing. But I hate wasting my hours on that. If it's only me, it means some weird conflict is happening somewhere. I'm still running on a machine that had Yosemite beta on it. Maybe a fresh install one weekend during a slow time is the way to go. If it's a problem affecting others I'll give it more thought.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.