kreierson

Experience

28,900

5 Best Reply Awards

  • Member Since 2 Years Ago
  • 309 Lessons Completed
  • 6 Favorites

2nd April, 2018

kreierson left a reply on Catch Laravel Custom Exception In Axios • 3 months ago

Damn it. I was working on the wrong Vue file. Idiot

kreierson left a reply on Catch Laravel Custom Exception In Axios • 3 months ago

Any Ideas?

30th March, 2018

kreierson left a reply on Catch Laravel Custom Exception In Axios • 3 months ago

I suppose it's worth mentioning that my axios request is inside the stripe request.

this.stripe.createToken(this.card, {
    name: this.formData.customer.full_name,
}).then(function(result) {
     self.formData.stripeToken = result.token.id;
     axios.post('/outfitter/api/customers/update-card', formData).then(function(response) {
         self.alert.success('Card updated!');
     }).catch(function(error) {
         console.log(error.response.data.errors);
     });
});

kreierson started a new conversation Catch Laravel Custom Exception In Axios • 3 months ago

I am storing a credit card on Stripe for a customer using axios.

axios.post('/outfitter/api/customers/update-card', formData).then(function(response) {
    self.alert.success('Card updated!');
}).catch(function(error) {
    console.log(error.response.data.errors);
});
                                

This submits the request with the stripe token to my controller. In my controller I create the customer on stripes end and associate the card.

I'm trying to catch a card declined error and throw a custom exception

try {
    $stripeCustomer = \Stripe\Customer::create([
        "description" => $customer->first_name . ' ' . $customer->last_name,
        "email" => $customer->email,
        "source" => $stripe_token, // obtained with Stripe.js
        "metadata" => [
            'outfitter_id' => Auth::user()->outfitter_id,
            'outfitter_name' => Auth::user()->outfitter->name
        ]
    ]);
} catch (\Stripe\Error\Card $e) {
    throw new StripeCardDeclinedException;
}

Custom Exception

public function render($request)
{
    return response()->json([
            'errors' => [
                'card_declined' => ['Card Declined']
            ]
    ], 422);
}

I want to return a json response similar to what the Laravel validator returns. In the network tab in Chrome, I am seeing the response: {"errors":{"card_declined":["Card Declined"]}} so this tells me it is working. But what isn't happening is the catch from my axios request isn't getting called so the errors are getting logged to the console.

Anyone run into this before?

28th March, 2018

kreierson left a reply on How To Get The Text Of The Selected Option Using Vue ? • 3 months ago

Html

<select name="customerName" v-model="selectedCustomer">
           <option v-for="customer in customers" value="customer">
                     {{customer.name}}
           </option> 
</select>
    {{selectedCustomer.name}}

JavaScript

data: {
    selectedCustomer: {
         id: '',
         name:'',
    },
    customers: [],
}

Did this on my phone so I didn't wrap the JavaScript inside a Vue instance but you should get the list. Just populate the customers array with some data and it should work.

Even if you are fetching data from the value it will work in this case, you'll be passing the entire selected customer object to your back end, which has the id of the customer.

18th February, 2018

kreierson left a reply on Mix Compile Issue • 5 months ago

Do you have sweet alert referenced twice? Maybe you still have your CDN reference. I have run into that before where I referenced it twice and it messes with stuff.

kreierson left a reply on Mix Compile Issue • 5 months ago

Does you vendor.js file come after or before the code calling the sweet alert?

kreierson left a reply on How To Display Or Transform [] Field To Array • 5 months ago

Implode(",", fieldname)

13th February, 2018

kreierson started a new conversation Sort By Nested Eager Load • 5 months ago

I'm looking to sort a nested eager load query.

Here is what I have tried so far:

Availability::
            with(['reservations' => function ($query) {
                $query->with(['customer' => function ($query) {
                    $query->orderBy('first_name');
                }]);
            }])->firstOrFail();
Availability::
            with(['reservations.customer' => function ($query) {
                    $query->orderBy('customer.first_name');
            }])->firstOrFail();

Availability is a single object which has many reservations. A reservation has a single customer.

I would like to order all the reservations by the customers first name. Any help would be greatly appreciated. Thanks

23rd January, 2018

kreierson left a reply on URL Parameters • 5 months ago

You wrote all that on your phone? That's awesome. This looks like a good solution, let me give it a go. Thank you for your time!

kreierson left a reply on URL Parameters • 5 months ago

@jcmargentina

That does make the public and private tabs active, however the conversation tab isn't active by default so the user will still have to click the conversation tab.

kreierson left a reply on MethodNotAllowedHttpException • 5 months ago

Is that your entire routes file? Have you made any changes? I'm looking for other routes that might be getting executed [email protected] above the routes you have listed.

kreierson left a reply on MethodNotAllowedHttpException • 5 months ago

Can you show us your entire routes file?

kreierson left a reply on MethodNotAllowedHttpException • 5 months ago

Also you need your csrf token in your form

<form id="form" class="form-horizontal form-bordered" method="POST" action="{{ $user->uuid ? route('user.edit', ['uuid' => $user->uuid]) : route('user.store') }}">
{{ csrf_field() }}
</form>

kreierson left a reply on MethodNotAllowedHttpException • 5 months ago

Are you posting to a different domain than your app?

If so maybe look into this https://github.com/barryvdh/laravel-cors

kreierson left a reply on MethodNotAllowedHttpException • 5 months ago

Hmmm... can you verify the endpoint you are hitting is correct when you click the button to post your form?

Open chrome devtools , go to the network tab. Under Headers verify the Request URL is hitting a route you have listed.

Post the Request URL here.

kreierson left a reply on MethodNotAllowedHttpException • 5 months ago

You are sending a post request to your endpoints and you only have patch endpoints. Either change your patch routes to post or add the method helper in your form.

Method helper example

<form method="POST" action="patchlink">
     {!! method_field('patch') !!}
     . . .
</form>

Change patch to post example

Route::post('/ubah', '[email protected]')->name('user.edit');
Route::post('/update', '[email protected]')->name('user.update'); 

kreierson started a new conversation URL Parameters • 5 months ago

This isn't Laravel related at all, but I seem to have better luck here than stack overflow.

I have a tab section with 4 tabs on one of my web pages. Inside that tab section I have another tab section with two tabs.

Parent tab section ids #ticket, #attachements, #conversation, #history

Conversation tab section #conversation tab has two tabs inside #public, #private

I'm trying to send a url in an email to show the conversation tab and within that show the private tab.

I can use this url to show the conversation tab no problem http://website.com/ticket/1233#conversation

How would I also show the nested private tab as well via url?

Below is some code for a basic visual

<div id="ticket></div>
<div id="attachments></div>
<div id="conversation>
    <div id="public"></div>
    <div id="private></div>
</div>
<div id="history></div>

18th January, 2018

kreierson left a reply on Filterby V-for With Array Of Objects • 6 months ago

I wouldn't populate the equipment dropdown until you select a category. Put an onchange event on the category dropdown, then when the category is changed, make a request to pull in the equipment with that category.

Maybe something like below

methods: {
            autoComplete(){
                this.category = [];
                this.equipment = [];
                this.csrf = document.querySelector("meta[name='csrf-token']").getAttribute("content");
                axios.get('/home/category',{params: {query: this.query}}).then(response => {
                    this.category = response.data;
                });

            },
            selectedCategory(category, id){
                $('#category').val(category);
                // Maybe pass the category id through your query parameter
                axios.get('/home/equipment',{params: {category_id: id}}).then(response => {
                    this.equipment = response.data;
                });
            },
            selectedMake(make,model){
                $('#make').val(make);
                $('#model').val(model);
            }
        }

kreierson left a reply on Sort A Collection By A Relationship Value • 6 months ago

Try adding the order by to your relationship

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

10th January, 2018

kreierson left a reply on How Is "class User Extends Authenticatable" Different From "class User Extends Model" • 6 months ago

Yep, see my snippet above, it extends the model class.

kreierson left a reply on Check If The Object Request Is Empty Before For Each • 6 months ago

Convert the contacts array to a collection:

$contacts = collect($request->contacts);

// Then either do this

$contacts->each(function($contact) {
    // Do Something
});

// or this

if(!$contacts->isEmpty()) {
    // Do Something
}

kreierson left a reply on Check If The Object Request Is Empty Before For Each • 6 months ago

If you pass a contacts variable from your controller to your view like this:

$contacts = Contacts::all();
return view('contacts', compact('contacts'));

Then you can do this:

@if(!$contacts->isEmpty())
<tr >
        <td> {!! Form::text('contacts[][first_name]',NULL, ['class' => 'form-control'] ) !!}        </td>
        <td> {!! Form::text('contacts[][last_name]',NULL, ['class' => 'form-control'] ) !!}</td>
        <td> {!! Form::text('contacts[][contact_email]',NULL, ['class' => 'form-control'] ) !!}</td>
        <td> {!! Form::text('contacts[][contact_phone]',NULL, ['class' => 'form-control'] ) !!}</td>
        <td> {!! Form::text('contacts[][contact_department]',NULL, ['class' => 'form-control'] ) !!}</td>
 </tr>
@endif

kreierson left a reply on Send Data To Vue Component From Blade Template File • 6 months ago

Can you show some code?

kreierson left a reply on Accessing Dynamic Arrays • 6 months ago

I wouldn't add contact_rows as a separate array, just use form.contacts.

<div v-for="contact in form.contacts">
    <input type="text" v-model="contact.fname">
    <input type="text" v-model="contact.lname">
</div>

then have your button that adds a new row to add to form.contacts instead of your other contact_rows array.

kreierson left a reply on How Is "class User Extends Authenticatable" Different From "class User Extends Model" • 6 months ago

The Illuminate\Foundation\Auth\User as Authenticatable is just a class that tacks on some additional traits Authenticatable, Authorizable, CanResetPassword.

The underlying class Illuminate\Foundation\Auth\User class also extends model giving you all the relational functionality you would expect if you were to simply extend Model.

Illuminate\Foundation\Auth\User Class:

class User extends Model implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;
}

kreierson left a reply on Vue + Axios + Delete Resource Gives Method Not Allowed • 6 months ago

Maybe try this in your axios request?

axios.delete('/admin/removeRole', { 
    data: { 
        role_id: this.role.id
    } 
}).then(response => { 
    swal('Deleted!', 'The role has been deleted.', 'success');
});

14th November, 2017

kreierson left a reply on Checking Array Length • 8 months ago

@tisuchi Thanks for the reply! Turns out I was an idiot and forgot I converted the array to an object :p

kreierson left a reply on Checking Array Length • 8 months ago

Figured it out. I forgot I was using reduce on the array to group the trips by date, which turned the trips array into an object.

self.trips = response.data.trips.reduce(function(r, a) {
                        r[a.start_date] = r[a.start_date] || [];
                        r[a.start_date].push(a);
                        return r;
                    }, Object.create(null));

I did this in case anyone else comes across this.

self.hasTrips = response.data.trips.toString();

Then did my v-show on the hasTrips property.

kreierson left a reply on Checking Array Length • 8 months ago

PS, I am not able to pass the trips in as a prop.

kreierson started a new conversation Checking Array Length • 8 months ago

I have a vue component with and initial data property set to an empty array.

data: function() {
            return {
                trips: [],
        }
}

Then in the mounted hook, I do a request and populate that array.

In my vue template, I want to show a table of the results if the trips array has any trips in it, and I want to show a div saying there are no trip available if the array is empty.

I am currently doing this

<table class="table table-borderless" v-show="trips.length">
    Table data
</table>

<p v-show="!trips.length">No trips available</p>

The

tag always shows up, event though I can see there are trips available in the Vue devtools. I understand it's probably initializing as an empty array, but shouldn't Vue pick up on the change and display the results when the array is eventually populated? How do I solve this?

Thanks!

1st November, 2017

kreierson left a reply on Use Relationship To Display User Name In Comment • 8 months ago

You need

Route::post('/blog/slug/comments/id', '[email protected]');

In your routes file.

kreierson left a reply on Use Relationship To Display User Name In Comment • 8 months ago

When you get your comments you have to pull in the user relationship.

    $comments = Comment::with('user')->where('post_id', $postId)->get();
        return response()->json(['comments' => $comments]);

Then you can do this

export default {
        data: function() {
            return {
               comments: [],
            }
        },
        mounted: function() {
            var self = this;    
            axios.get('/post/'+slug+'/comments/').then(function(response) {
                self.comments = response.data.comments;
            });
        }
        
    }

Then you can do this

<div v-for="comment in comments">
        <h4>{{comment.user.name}}</h4>
        <p>{{comment.text}}</p>
    </div>

kreierson left a reply on Use Relationship To Display User Name In Comment • 8 months ago

Maybe something like this...

    export default {
        data: function() {
            return {
               comments: [],
            }
        },
        mounted: function() {
            var self = this;    
            axios.get('/post/'+slug+'/comments/').then(function(response) {
                self.comments = response.data.comments;
            });
        }
        
    }

kreierson left a reply on Best Way Of Sending Flash Message From Laravel To Vue • 8 months ago

Cool, another thing I have done is check for errors on a master layout page. Create a footer section and extend the footer on each page. Then you don't have to pass it in as a prop on every component, you just handle it with a quick script.

    // Master layout
    <div class="errors" style="display:none;">
        <ul>
            @foreach($errors as $error)
                <li>{{$error}}</li>
            @endforeach
        </ul>
    </div>
    @yield('content')

    @yield('footer')

//Page where your component lives
@section('content')
    <your-component></your-component>
@endsection

@section('footer')
    @if(session('errors'))
          <script>
              // Code to make errors visible
          </script>
    @endif
@endsection

kreierson left a reply on PUT/PATCH Request Not Getting The Request Payload • 8 months ago

Is there another route above this route that maybe has the same path and that route is getting hit first? Just a thought, I run into this all the time.

Route::patch('/items/{item}', '[email protected]'); //This will get hit first

Route::resource('/items', 'ItemcontrollerApi'); //This will also get hit before the put request

// move this line above the two before this
Route::put('/items/{item}', '[email protected]')->name('items.update');

kreierson left a reply on Use Relationship To Display User Name In Comment • 8 months ago

I don't think you would want to pull the comments for a post from an index method on a CommentController.php. The index method assumes you are pulling all resources, meaning all comments with no regard to which post they are for. I would do a PostCommentController.php and hit the index method, that way it's a little more expressive on what you are grabbing. In this case all comments for a post. You would still need to pass the id of the post to the index method.

class PostCommentsController
{
    public function index($postId)
    {
        $comments = Comment::where('post_id', $postId)->get();
        return response()->json(['comments' => $comments]);
    }
}

kreierson left a reply on Best Way Of Sending Flash Message From Laravel To Vue • 8 months ago

Ah, so if you're flashing a message to the session similar to this:

$request->session()->flash('error', 'Email already exists!');

Maybe you can do this?

<component :prop="{{session()->get('error')}}"></component>

kreierson left a reply on Why Redirecting Me To Other Site • 8 months ago

Maybe check your session lifetime in config.session.

Also are you working on Windows? I've had this happen to me before, and ended up installing homestead and running my app on that instead of using php artisan serve and I haven't had that issue since.

kreierson left a reply on Catch Event On Table Row Component ? • 8 months ago

I'm assuming there is a method somewhere in the child component that updates the detail. Inside that method or where ever that detail gets update, you can emit an event.

updateDetail: function() {
    this.$emit('detail-updated', payload);
}

Then on your parent component

    // Listen for the detail-updated event inside the child, then call updateDetail
    // on the parent
    <child-component @detail-updated="updateDetail"></child-component>
    updateDetail: function(payload) {
        //do what needs to be done.
    }

kreierson left a reply on Best Way Of Sending Flash Message From Laravel To Vue • 8 months ago

As @vapenation said it should come from your backend. I usually create a form request to handle the validation, or you can put that in your controller. Then Laravel will respond with a 422 allowing you to catch that error response and display the error message. Here is a video that goes through that exact process. https://laracasts.com/series/learn-vue-2-step-by-step/episodes/19

31st October, 2017

kreierson left a reply on Vue Google Maps And Foreach Statment On Markers • 8 months ago

Total shot in the dark but might give you an idea. I'm not that great at javascript.

var newMarkers = this.markers.map(function (marker) { //Map over the markers
                    for (i = 0; i < this.markers.length; i++) { // loop over the markers
                        if (this.markers.indexOf(marker) != this.markers[i]) { // Make sure we don't compare the marker to itself
                            if(Object.is(marker.position, this.markers[i].position)) { //compare the position on the marker
                                return { // if the position on the markers match, build a new marker adding 2
                                    position: {
                                        lat: marker.position.lat+2,
                                        lng: marker.position.lat+2,
                                    },
                                    infoText: marker.infoText
                                }
                            }
                        }
                        return marker;
                    }
                });

kreierson left a reply on Vue Google Maps And Foreach Statment On Markers • 8 months ago

If you're just dumping these values out to a table

<table>
    <tr>
        <td>Lat</td>
        <td>Lng</td>
        <td>Text</td>
    </tr>
    <tr v-for="marker in markers">
        <td>{{marker.position.lat}}</td>
        <td>{{marker.position.lng}}</td>
        <td>{{marker.infoText}}</td>
    </tr>
</table>

Or if you need to loop through them in a method or mounted function just use javascript

this.markers.forEach(function(marker) {
      console.log(marker);
});

kreierson left a reply on PUT/PATCH Request Not Getting The Request Payload • 8 months ago

try putting a / before items in your axios request?

export const updateItem = ({ commit, dispatch }, payload) => {
    return axios.put('/items/' + payload.id, payload).then((response) => {
            return Promise.resolve(response)
        })
}

kreierson left a reply on Use Relationship To Display User Name In Comment • 8 months ago

Maybe something along these lines if you want to grab the post along with all the comments. This is also assuming you have a relationship called comments on your post model and a relationship called user on your comments model.

From your posts controller

public function show($id) {

    $post = Post::with('comments.user')->where('id', $id)->firstOrFail();
    return response()->json(['post' => $post]);
}

    export default {
        data: function() {
            return {
                post: {},
            }
        },
        mounted: function() {
            var self = this;    
            axios.get('/post/'+post_id).then(function(response) {
                self.post = response.data.post;
            });
        }
        
    }

Then where ever you are dumping out the comments on your page

    <div v-for="comment in post.comments">
        <h4>{{comment.user.name}}</h4>
        <p>{{comment.text}}</p>
    </div>

kreierson left a reply on Why Redirecting Me To Other Site • 8 months ago

Maybe check the APP_URL in your .env file?

kreierson left a reply on V-model With Transnational Data • 8 months ago

I guess I can v-model on the id of the package in the reservation and package table. Then do array.filter() to get the selectedPackage from the available packages to show pricing info on the page.

30th October, 2017

kreierson started a new conversation V-model With Transnational Data • 8 months ago

I have a system where a customer can make a reservation for a trip. On that reservation they can choose a package. Below is an example of my tables for these two objects.

Reservations Table | id | customer_id | price | no_of_people | package_id | package_name | package_price | | --- | --- | --- | --- | --- | --- | --- | | 1 | 550 | 15000 | 2 | 1 | Lodging | 9000 | | 2 | 499 | 15000 | 2 | 2 | Ultimate | 13000 |

Package Table | id | name | price | | --- | --- | --- | | 1 | Lodging | 9000 | | 2 | Ultimate | 13000 |

Creating a reservation and using v-model on the select box is straight forward

<select class="form-control form-control-sm" v-model="reservation.package">
    <option v-for="package in available_packages" :value="package">
          {{package.name}}
    </option>
</select>
                                        

My issue comes into play when I am building the edit form. I want them to be able to update the package and if i use v-model just like above, I run into an issue if the admin decides to update the price or name of the package. If the name or price is updated, the name and most importantly the price gets updated. When the reservation was made, the customer expects to pay that price, but if the company updates the package, now the relationship is looking at the updated price.

Since the reservation is a transaction, I need to capture that price on the reservation at the time of booking, so how would I use v-model on a select box when I need to show pricing information from the reservation table for the selected package, and not the price from the package table.

I hope that makes sense. Thanks!

Edit Your Profile
Update

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