kreierson

kreierson

Member Since 3 Years Ago

Experience Points 31,170
Experience
Level
Lessons Completed 329
Lessons
Completed
Best Reply Awards 5
Best Answer
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.

02 Aug
4 months ago

kreierson left a reply on Storing Reservation Information

I wonder if something like this would be a good way to go. https://github.com/gazugafan/laravel-temporal

23 Jul
4 months ago

kreierson left a reply on Storing Reservation Information

Ah, nice. I had it backwards. I was trying to capture the current price at the time the reservation was made. But by storing the pricing like you mentioned I wouldn't need to worry about it. Thanks for the input @Cronix

kreierson started a new conversation Storing Reservation Information

I'm building a reservation system for a fishing outfitter. Here is the set up so far.

An outfitter can schedule many outings. Outings are times of the day for example 7am to 4pm. An outing has spots available so people can reserve a spot. These outings have a price attached so each outing for example could be $150 per spot.

This outfitter also offers packages, so for example Lodging Package. This package will also have a price attached to it. Lets say the Lodging Package is $100.

A reservation can reserve many outings and it can also have a package.

Below are my table structures.

Reservations: id, package_id, customer_id, number_of_people

Outings id, start_date_time, end_date_time, max_number_of_people, price 1, 2018-01-01 07:00:00 2018-01-01-16:00:00 30 150 2, 2018-01-02 07:00:00 2018-01-02-16:00:00 30 150 3, 2018-01-03 07:00:00 2018-01-03-16:00:00 30 150

Packages id, name, description, price 1 Lodging Includes Hotel 100

I want to book a reservation from Jan 1st - 3rd, so a 3 day reservation for 2 people. The above outings table are the outings that are scheduled and available to make a reservation against.

Here is what the reservation would look like. id, package_id, customer_id, number_of_people 1, 1, 1, 2

Then a pivot table linking the reservation to the 3 outings. reservation_id, outing_id 1, 1 1, 2 1, 3

Now my question. What if the outfitter changes the price of the outing or package. I still want that reservation to cost the same as when it was made. So for a 3 day reservation for 2 people with the lodging package it should cost $1,000.000

Basically I'm looking for the best way to store reservation pricing information so if the master data (Package or Outing) changes, I still have reference to what that data was at the time of the reservation.

I was thinking of storing the pricing information on the pivot table for the reservation to outing relationship and I think that would work well. But not sure about the reservation to package relationship.

Let me know if you have any ideas.

02 Apr
8 months ago

kreierson left a reply on Catch Laravel Custom Exception In Axios

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

30 Mar
8 months ago

kreierson left a reply on Catch Laravel Custom Exception In Axios

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

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?

28 Mar
8 months ago

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

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.

18 Feb
9 months ago

kreierson left a reply on Mix Compile Issue

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

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

Implode(",", fieldname)

13 Feb
10 months ago

kreierson started a new conversation Sort By Nested Eager Load

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

23 Jan
10 months ago

kreierson left a reply on URL Parameters

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

@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

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

Can you show us your entire routes file?

kreierson left a reply on MethodNotAllowedHttpException

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

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

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

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

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>
18 Jan
10 months ago

kreierson left a reply on Filterby V-for With Array Of Objects

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

Try adding the order by to your relationship

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

kreierson left a reply on How Is "class User Extends Authenticatable" Different From "class User Extends Model"

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

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

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 Accessing Dynamic Arrays

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"

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

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');
});
14 Nov
1 year ago

kreierson left a reply on Checking Array Length

@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

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

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

kreierson started a new conversation Checking Array Length

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!

01 Nov
1 year ago

kreierson left a reply on Use Relationship To Display User Name In Comment

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

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

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

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

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

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

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

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 ?

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

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

31 Oct
1 year ago

kreierson left a reply on Vue Google Maps And Foreach Statment On Markers

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

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

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

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>