ajsmith_codes

ajsmith_codes

Member Since 1 Year Ago

Experience Points
15,720
Total
Experience

4,280 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
111
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 4
15,720 XP
Aug
03
1 day ago
Activity icon

Replied to Is There A Way To Set A Value And Pass With @click To Vue Component?

@bugsysha What do you mean by "extract another component"? I'm still learning the lingo. :)

Jul
31
4 days ago
Activity icon

Started a new Conversation Is There A Way To Set A Value And Pass With @click To Vue Component?

I have a view that lists phone numbers and is populated by an array. When a user clicks on Edit for a particular phone number, I want to pass the phone's id to a vue instance. Is this possible?

Here is the view button, and I'm not certain how to set the value of the phone id.:

 <a href="/phone/edit"
                                   id="phone"
                                   @click.prevent="$modal.show('edit-phone')">
                                    Edit</a>

And here is where I call the modal in my view:

<edit-phone-component
    :customer="{{ $customer->id }}">
</edit-phone-component>

And here is the vue component:

New Phone Number

    <div
        id="edit-phone"
        class="text-center">
        <form
            @submit.prevent="handleSubmit">
            <div
                v-if="errors.length">
                <div
                    class="text-red-700 ml-6">
                    <ul>
                        <li v-for="error in errors">
                            {{
                            error
                            }}
                        </li>
                    </ul>
                </div>
            </div>

            <div
                class="flex">
                <div
                    class="flex-1 m-4">
                    <div
                        class="mb-4">

                        <label

                            class="text-sm block mb-2">
                            Phone
                            Type
                        </label>

                        <select
                            class='form-control shadow'
                            v-model='type'
                            id="type">
                            <option
                                value='0'
                                disabled>
                                Select
                                Type
                            </option>
                            <option
                                v-for='type in types'
                                :value='type.type'>
                                {{
                                type.type
                                }}
                            </option>
                        </select>

                    </div>
                    <div
                        class="mb-4">
                        <label>
                            Number
                        </label>
                    </div>
                    <div
                        class="mb-4">
                        <input
                            type="text"
                            class="shadow"
                            v-model="phone"
                            id="phone"
                            value="phone"
                        />
                    </div>
                    <div
                        class="mb-4">
                        <label>
                            Extension
                        </label>
                    </div>
                    <div
                        class="mb-4">
                        <input
                            type="text"
                            class="shadow"
                            v-model="extension"

                        />
                    </div>

                    <div
                        class="mb-4">

                        <button
                            class="button-blue"
                            type="submit">
                            Submit
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</modal>
export default { data: function () { return { type: 0, types: [], extension: '', phone: '', errors: [], modalShow: true }; }, methods: { handleSubmit: function (e) { if (this.type && this.phone && this.extension) {
                axios.post('/phone/store', {
                    type: this.type,
                    extension: this.extension,
                    vendor: this.vendor,
                    customer: this.customer
                })
                    .then((response) => {
                        $('#success').html(response.data.message)
                        this.modalShow = false
                        window.location.reload()
                    })
                    .catch(error => {
                        console.log(error)
                    });
            }

            this.errors = [];

            if (!this.phoneNumber) {
                this.errors.push('Please enter a phone number.');
            }
            if (!this.type) {
                this.errors.push('Please choose a type.');
            }


            e.preventDefault();
        }
    },
    mounted() {
        function getContactTypes() {
            return axios.get('/api/getContactTypes');
        }

        function getPhone(customer, id) {
            return axios.get('/api/getPhone',{
                params: {
                    id: phoneId
                }
            });
        }

    },
    props: ['vendor', 'customer', 'phoneId']

};
Jul
29
6 days ago
Activity icon

Replied to Get Polymorphic Data In Controller?

@click Also, I'm trying to get a specific phone number when I click on my edit button. The edit button opens the modal.

Is there a different way to pass the phone number's id to the vue component?

EDIT: Here is the click event:

<a href="/phone/edit" @click.prevent="$modal.show('edit-phone')"> Edit

Can I pass an id through that?

Activity icon

Replied to Get Polymorphic Data In Controller?

@click Sorry, yes, I did change that. That was a typo here on my part.

Activity icon

Replied to Get Polymorphic Data In Controller?

@click Hi. Yes, $customer->phone gives results in the view.

I changed the relationship to phones and changed with('phoneable') to with('phone'). I get back an empty array. I checked and there definitely is a phone number associated with the customer.

Activity icon

Started a new Conversation Get Polymorphic Data In Controller?

I have set up a many-to-many polymorphic relationship for phone numbers, called phoneable. I am working in the controller and trying to retrieve the phone numbers associated with a particular customer. I can't seem to get it to work. I either get errors or an empty json array.

If I try to retrieve the relationship in the view, it works, so I think I have the relationship setup correctly.

Here is the controller:

    $data = Customer::where('id', $request->customer)
    ->with(['phoneable'])
    ->get();


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

Customer Model:

public function phone()
{

    return $this->morphToMany(Phone::class, 'phoneable');

}

Phone Model:

public function customer()
{

    return $this->morphedByMany(Customer::class, 'phoneable')
        ->withTimestamps();

}

Anyone know the trick to get this to work in my controller?

Jul
28
1 week ago
Activity icon

Replied to Polymorphic Relationship Returns Object.

@jbloomstrom Thanks! That did the trick!

Jul
27
1 week ago
Activity icon

Started a new Conversation Polymorphic Relationship Returns Object.

Using Laravel 7.

I make an api call to obtain a list of contacts when a user chooses a customer. The response is returned via json_encode.

For some reason, I keep getting an object, which is not working with my custom javascript. Maybe someone can see what I'm doing wrong?

Here is the JS Code:

$('select[name="customer_id"]').on('change', function () {

    var customerId = $(this).val();

    if (customerId) {
        $.ajax({
            url: '/api/customer/contacts/get/' + customerId,
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                $('#loader').css("visibility", "visible");
            },

            success: function (data) {

                $('input[name="email"]').val('');

                $('select[name="contact_id"]').empty();

                $('select[name="contact_id"]').append('<option value="Choose">Choose Contact</option>');

                $.each(data, function (key, value) {

                    $('select[name="contact_id"]').append('<option value="' + key + '">' + value + '</option>');

                });
            },
            complete: function () {
                $('#loader').css("visibility", "hidden");
            }
        });
    } else {
        $('select[name="customer_id"]').empty();
    }

});

Here is the controller:

    $customer = Customer::where('id', $id)->first();

    $contacts = $customer->contacts;


    return json_encode($contacts);

And here is the form select:

                        <select
                            name="contact_id"
                            class="shadow text-sm text-center"
                        >
                            @if(old('contact_id'))
                                @foreach($contacts as $contact)

                                    <option
                                        value="{{ old('contact_id') }}"
                                        {{ $contact->id == old('contact_id') ? 'selected' : ''}}>
                                        {{ $contact->name }}
                                    </option>

                                @endforeach

                            @else

                                <option>

                                </option>

                            @endif

                        </select>
Activity icon

Replied to How To Close Modal From Vue Method ?

@cometads I struggled with this for days until I found your answer. Thanks!!

Activity icon

Replied to Trouble Combining Two Vue Forms.

I scrapped this idea and started from scratch.

Jul
23
1 week ago
Activity icon

Replied to Trouble Combining Two Vue Forms.

Forgot to include the crmForm.js

class CrmForm { constructor(data) { this.originalData = JSON.parse(JSON.stringify(data));

    Object.assign(this, data);

    this.errors = {};
    this.submitted = false;
}

data() {
    return Object.keys(this.originalData).reduce((data, attribute) => {
        data[attribute] = this[attribute];

        return data;
    }, {});
}

post(endpoint) {
    return this.submit(endpoint);
}

patch(endpoint) {
    return this.submit(endpoint, 'patch');
}

delete(endpoint) {
    return this.submit(endpoint, 'delete');
}

submit(endpoint, requestType = 'post') {
    return axios[requestType](endpoint, this.data())
        .catch(this.onFail.bind(this))
        .then(this.onSuccess.bind(this));
}

onSuccess(response) {
    this.submitted = true;
    this.errors = {};

    return response;
}

onFail(error) {
    this.errors = error.response.data.errors;
    this.submitted = false;

    throw error;
}

reset() {
    Object.assign(this, this.originalData);
}

}

export default CrmForm;

Activity icon

Started a new Conversation Trouble Combining Two Vue Forms.

Laravel 7, Vue 2.6.11

I found a tutorial for creating a vue componant that dynamically populates countries, states, and cities. I have another vue component that is a modal form for creating a new record. It was used to create a new project.

I'm trying to combine them into one, but when I try to move country, city, and state into the form: new CrmForm, I can't access the functions that populate the selects.

Obviously I'm still very new at this. Any help is appreciated. :)

Address

    <form
        @submit.prevent="submit">
        <div
            class="container">
            <div
                class="row justify-content-center">
                <div
                    class="col-md-8">
                    <div
                        class="card">
                        <div
                            class="card-header">
                            Address
                        </div>

                        <div
                            class="card-body">
                            <div
                                class="form-group">
                                <label>Select
                                    Country:</label>
                                <select
                                    class='form-control'
                                    v-model='country'
                                    @change='getStates()'>
                                    <option
                                        value='0'>
                                        Select
                                        Country
                                    </option>
                                    <option
                                        v-for='data in countries'
                                        :value='data.id'>
                                        {{
                                        data.name
                                        }}
                                    </option>
                                </select>
                            </div>

                            <div
                                class="form-group">
                                <label>Select
                                    State:</label>
                                <select
                                    class='form-control'
                                    v-model='state'
                                    @change='getCities()'>
                                    <option
                                        value='0'>
                                        Select
                                        State
                                    </option>
                                    <option
                                        v-for='data in states'
                                        :value='data.id'>
                                        {{
                                        data.name
                                        }}
                                    </option>
                                </select>
                            </div>
                            <div
                                class="form-group">
                                <label>Select
                                    City:</label>
                                <select
                                    class='form-control'
                                    v-model='city'>
                                    <option
                                        value='0'>
                                        Select
                                        City
                                    </option>
                                    <option
                                        v-for='data in cities'
                                        :value='data.id'>
                                        {{
                                        data.name
                                        }}
                                    </option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <footer
            class="m-6 flex justify-end">

            <button
                type="button"
                class="mr-2 button-is-outlined"
                @click="$modal.hide('new-address')">
                Cancel
            </button>

            <button
                class="button-blue">
                Create
                Address
            </button>

        </footer>
    </form>
</modal>

import CrmForm from './CrmForm';

export default {
    mounted() {
        console.log('Component mounted.')
    },
    data() {
        return {
            form: new CrmForm({
                country: '',
                state: '',
                city: '',
            }),
            country: 0,
            countries: [],
            state: 0,
            states: [],
            city: 0,
            cities: []
        };
    },
    methods: {

        getCountries: function () {
            axios.get('/api/getCountries')
                .then(function (response) {
                    this.countries = response.data;
                }.bind(this));

        },
        getStates: function () {
            axios.get('/api/getStates', {
                params: {
                    country_id: this.country
                }
            }).then(function (response) {
                this.states = response.data;
            }.bind(this));
        },
        getCities: function () {
            axios.get('/api/getCities', {
                params: {
                    state_id: this.state
                }
            }).then(function (response) {
                this.cities = response.data;
            }.bind(this));
        },
        async submit() {
            this.form.submit('/addresses/store')
                .then(response => location = response.data.message);
        }
    },
    created: function () {
        this.getCountries()
    }
}
Jul
22
1 week ago
Activity icon

Replied to Error: Call To Undefined Method StdClass With Polymorphic Relationships.

@bobbybouwmann Thanks! That solved that particular issue. Now I just have to figure out why the data isn't saving. But that's another topic. :)

Activity icon

Started a new Conversation Error: Call To Undefined Method StdClass With Polymorphic Relationships.

Working with Laravel 7.

I have a many to many polymorphic relationship between Addresses and Vendors. While creating a vendor, I want to attach an address. I must be doing something wrong with my code.

Controller: $rules = [ 'name' => 'required', 'notes' => 'nullable', 'type' => 'nullable', 'line1' => 'nullable', 'line2' => 'nullable', 'country' => 'nullable', 'city' => 'nullable', 'state' => 'nullable', 'zip' => 'nullable', ];

    $customMessages = [
        'name.required' => 'The Vendor Name is required.',
    ];


    $vendor = \request()->validate($rules, $customMessages);

    Vendor::create($vendor);

    $vendor = \DB::table('vendors')->latest()->first();

    if ($request->line1 != ""){
        
        $address = new Address();
        $address->type = $request->type;
        $address->line1 = $request->line1;
        $address->line2 = $request->line2;
        $address->city = $request->city;
        $address->state = $request->state;
        $address->zip = $request->zip;
        $address->country = $request->country;

        $vendor->address()->save($address);

    }

Vendor Model:

public function addresses()
{

    return $this->morphToMany('App\Address', 'addressable');

}

Address Model:

public function vendor(){

    return $this->morphedByMany(Vendor::class, 'addressable');

}
Jul
17
2 weeks ago
Activity icon

Replied to Trouble Retrieving Old Value Of Select When Editing.

@snapey I send only the contacts associated with that Customer.

Activity icon

Replied to Trouble Retrieving Old Value Of Select When Editing.

@snapey I ran into a little problem with the code. The Customer Contact only brings up the current contact in the dropdown. Is there a way to show all contacts related to that customer? I tried this but it's still only showing the contact listed in the order record:

$contacts = Contact::orderBy('name')->where('active', true)->where('id', $order->customer_id)->get();

Jul
16
2 weeks ago
Activity icon

Replied to Trouble Retrieving Old Value Of Select When Editing.

@snapey "Why any different?" I think to me it's because what you said, that the model does not yet exist. I wasn't sure where to go with that. I will look at the reference you sent. Thanks much!!

Activity icon

Replied to Trouble Retrieving Old Value Of Select When Editing.

@snapey Nevermind, I got it. :)

                        <select
                            name="contact_id"
                            class="shadow text-sm text-center"
                        >
                            @if(old('contact_id'))
                                @foreach($contacts as $contact)

                                    <option value="{{ old('contact_id') }}"
                                        {{ $contact->id == old('contact_id') ? 'selected' : ''}}>
                                        {{ $contact->name }}
                                    </option>

                                @endforeach

                            @else

                            <option>

                            </option>

                                @endif

                        </select>
Activity icon

Replied to Trouble Retrieving Old Value Of Select When Editing.

@snapey One last question. How would you use this for a create view instead of an edit?

Activity icon

Replied to Trouble Retrieving Old Value Of Select When Editing.

@snapey The select option is named 'contact_id'. I changed it in the code and it's working! Thanks!

Activity icon

Replied to Trouble Retrieving Old Value Of Select When Editing.

@jlrdw Correct, I am posting with the regular form submit. I only use ajax to populate the dropdown fields.

Activity icon

Replied to Trouble Retrieving Old Value Of Select When Editing.

@snapey Hey, Snapey! Always nice to see you posting.

I tried that and couldn't get it to work. I think you might be able to help pinpoint what I'm missing:

The orders table has the contact_id stored in it. Each order has one contact, but each contact can have many orders. If I use old(), I can get the contact_id, but not the contact name, which is what I show in the dropdown.

Here is my dropdown currently:

      <option
                                value="{{ $order->contact_id  }}">
                                {{ $currentContact->name  }}
                            </option>

I am pulling the contact's name via a variable that I check when I load the edit view. If I change the contact, I only have the contact_id. I'm not certain how to pull up the contact's name after validation fails. I looked into pivot tables, but it's a one to many, not many to many.

I'm probably confusing everyone. Sorry!

Activity icon

Replied to Trouble Retrieving Old Value Of Select When Editing.

@jlrdw Thanks for the info. That could help with my create form, but not with edit. Sorry if I'm confusing. I'll try to explain it a bit better:

I go to edit a sales order. The values populate from the database correctly. If I hit refresh or save right now, it's fine because I didn't change the values. They still populate correctly.

However, if I edit the form and change the customer and contact, then hit refresh or save, it brings back the data from the database, not the session or request.

Does that make more sense?

Activity icon

Started a new Conversation Trouble Retrieving Old Value Of Select When Editing.

I have a form to edit a sales order. If the user changes the Customer, I use javascript to populate the select options for the customer contacts that are linked to that customer. That part works great.

PROBLEM: When validation fails, I can't retrieve the customer contact's name to send back to the form.

The Sales Order table stores the contact_id, not the contact name, otherwise I think this would be easier to pull up.

Here is the form option:

{{ $currentContact->name }}

$currentContact is a variable I set in the controller so that I have the name of the contact.

Here is the validation code:

    $rules = [
        'number' => 'required',
        'revision' => 'nullable',
        'expedited' => 'nullable',
        'requested_ship_date' => 'required',
        'customer_id' => 'required',
        'contact_id' => 'required',
        'payment_type' => 'nullable',
        'department_id' => 'required',

    ];

    $customMessages = [
        'number.required' => 'The Sales Order number is required.',
        'customer_id.required' => 'Please choose a customer.',
        'contact_id.required' => 'Please choose a contact.',
        'requested_ship_date.required' => 'You must enter a ship date.',
        'requested_ship_date.yesterday' => 'The requested ship date must be today or after.',
        'department_id.required' => 'Please choose a department.'
    ];

    $validator = Validator::make($rules, $customMessages);

    if ($validator->fails()) {
        return redirect($order->path() . '/edit')
            ->withErrors($validator)
            ->withInput($request, $currentContact);
    }

I try to send back the contact's name via $currentContact, but no luck.

I have tried using 'old' and that doesn't work. I tried looking into sessions, but I couldn't find anything helpful for my situation. I'm very frustrated and about to give up.

Jul
15
2 weeks ago
Activity icon

Replied to Retrieve Old Value Of Select - Using Ajax/javascript - Laravel 7

@deepu07 I tried it in the view and get Undefined variable.

Jul
10
3 weeks ago
Activity icon

Replied to Can't Call Method From Controller.

@sergiu17 Wow! Something so simple gave me such a headache. Thank you!!

Activity icon

Started a new Conversation Can't Call Method From Controller.

I have multiple controllers where I call methods on models like this: $someVariable->callToMethod();

I do this a lot, but I can't get this to work today. I get this error: Property [expedited] does not exist on the Eloquent builder instance.

Controller:

 $order = Order::where('id', $id);

    $expedited = $request->expedited;
    $originalValue = $order->expedited;

    if ($expedited != $originalValue) {
        request('expedited') ? $order->expedited() : $order->notExpedited();
    }

Model:

public function expedited(){

    $this->update(['expedited' => true]);
}

public function notExpedited(){

    $this->update(['expedited' => false]);
}
Activity icon

Replied to Gantt Chart Or Calendar For Laravel 7?

Posting this here for future users: I dropped Fullcalendar after many, many failed attempts and time spent. I ended up using the Gantt chart from DHTMLX. They also have a calendar that works great (called scheduler).

https://docs.dhtmlx.com/?_ga=2.171122720.1223336188.1594397908-2053445720.1585665055

Activity icon

Awarded Best Reply on Please Help With Route!

Nevermind, I figured it out. I was missing /edit in the web route.

Activity icon

Awarded Best Reply on Laravel 6 - TDD App - Table Includes App\Task As Subject_type?

It turns out that this is normal. It was part of how Laravel knows which model the activity belongs to.

Activity icon

Replied to Laravel 6 - TDD App - Table Includes App\Task As Subject_type?

It turns out that this is normal. It was part of how Laravel knows which model the activity belongs to.

Activity icon

Awarded Best Reply on Laravel 6 - TDD App - Expected Status Code 403 But Received 200.

Thanks, everyone! I had missed adding $this->signIn() to that particular test. After that, it worked.

Activity icon

Replied to Retrieve Old Value Of Select - Using Ajax/javascript - Laravel 7

@deepu07 Does the php code go into the controller or view?

Jul
08
3 weeks ago
Activity icon

Replied to Data Not Passing To Details View.

@michaloravec Your first one works. Thanks!

Activity icon

Started a new Conversation Data Not Passing To Details View.

I've done this many times and it works, but I'm missing something here. I bet it's very simple, but I can't seem to pinpoint it.

When on the index view, the user clicks on the Details link:

Details

User is successfully redirected to the Show view, but the $salesOrder data isn't there EXCEPT for one value: ship_date.

However, if I do this:

return $salesOrder;

it comes back empty. Not event the ship date is showing.

Controller Code:

public function show(SalesOrder $salesOrder)
{

    return view('salesorders.show', compact('salesOrder'));
}

I tried to do this:

public function show($id)
{

    $salesOrder = SalesOrder::where('id', $this->id);

    return view('salesorders.show', compact('salesOrder'));
}

and get Undefined property: App\Http\Controllers\SalesOrdersController::$id

This gives me the same error:

public function show(SalesOrder $salesOrder)
{

    $salesOrder = SalesOrder::where('id', $this->id);

    return view('salesorders.show', compact('salesOrder'));
}

Route:

Route::get('/salesorders/{id}', '[email protected]');

Activity icon

Replied to Field Doesn't Have Default Value.

I got it to work! With @snapey code, I had the relationship in the User model as salesorders instead of salesorder. Once I removed the s, it worked!

Activity icon

Replied to Field Doesn't Have Default Value.

@tomasosho I tried to do that, but I must have the code wrong.

@snapey I tried to add your line of code and got this error:

Call to undefined method App\User::salesorder()

Jul
07
4 weeks ago
Activity icon

Started a new Conversation Field Doesn't Have Default Value.

I can't figure out what I'm doing wrong here.

I use a form to create a new sales order. Upon submit, I want to store the user_id in the Salesorder table so I know who created the order. However, I keep getting that error message about default value.

Can you see what I'm doing wrong here?

    $user_id = $request->get('user_id');

    $rules = [
        'number' => 'required',
        'customer_id' => 'required',
        'contact_id' => 'required',
        'payment_type' => 'nullable',
        'department_id' => 'required',
        'requested_ship_date' => 'required|after:yesterday',
    ];

    $customMessages = [
        'number.required' => 'The Sales Order number is required.',
        'customer_id.required' => 'Please choose a customer.',
        'contact_id.required' => 'Please choose a contact.',
        'requested_ship_date.required' => 'You must enter a ship date.',
        'requested_ship_date.yesterday' => 'The requested ship date must be today or after.',
        'department_id.required' => 'Please choose a department.'
    ];

    $salesorder = \request()->validate($rules, $customMessages);


    SalesOrder::create($salesorder);
Activity icon

Started a new Conversation Two Tables With Sometimes Relationship?

This is a weird one for me. I have two tables: Events and Absences. The idea here is that when an employee requests PTO, there is a record inserted into both tables, BUT, only if the absence is today or after. Why put something on the Event calendar if it's passed, right?

The events table may have other events as well, such as meetings, office closing etc., which are not absences.

So, not all events are absences, and not all absences are events. Make sense? What is the best way to handle this?

Here are the tables.

Events: id user_id text (used for the calendar, such as "AJ out at 1pm") start_date end_date type (PTO or another type of event)

Absences: id user_id event_id start_date end_date status hours (number of paid pto hours requested)

I need to be able to update the related event if a user changes their absence request. I'm having difficulty setting up the proper relationship for these two tables.

Here is what I have in the models.

Absence model:

public function events(){

    return $this->belongsTo(Event::class);

}

Event Model:

public function absences(){

    return $this->belongsTo(Absence::class);

}

Am I on the right track here? I can't get the relationships to work in the view or when I try to update the records.

Activity icon

Replied to Two Checkboxes On The Same Form Don't Work.

P.S. Thanks to everyone for helping!

Activity icon

Awarded Best Reply on Two Checkboxes On The Same Form Don't Work.

I finally figured it out. It was a couple things.

  1. I had to remove value from the input. Otherwise, I was overriding the checkbox value during post.
  2. I was validating the form before I checked for the status of the checkbox.

Here is the working checkbox:

  <input
                                type="checkbox"
                                name="salary"
                                class="shadow my-5"
                                {{ $user->salary ? 'checked' : '' }} >

Here is the working controller code:

  //original value of checkbox
    $originalSalaryValue = $user->salary;

    dd($originalSalaryValue);

    $salary = request('salary');


    if ($salary != $originalSalaryValue) {
        request('salary') ? $user->salary() : $user->notSalary();
    }


    //original value of checkbox
    $originalValue = $user->active;

    $active = request('active');


    if ($active != $originalValue) {
        request('active') ? $user->activeUser() : $user->inactiveUser();
    }
    $user->update($this->validateRequest());

    return redirect('admin/users');
Activity icon

Replied to Two Checkboxes On The Same Form Don't Work.

I finally figured it out. It was a couple things.

  1. I had to remove value from the input. Otherwise, I was overriding the checkbox value during post.
  2. I was validating the form before I checked for the status of the checkbox.

Here is the working checkbox:

  <input
                                type="checkbox"
                                name="salary"
                                class="shadow my-5"
                                {{ $user->salary ? 'checked' : '' }} >

Here is the working controller code:

  //original value of checkbox
    $originalSalaryValue = $user->salary;

    dd($originalSalaryValue);

    $salary = request('salary');


    if ($salary != $originalSalaryValue) {
        request('salary') ? $user->salary() : $user->notSalary();
    }


    //original value of checkbox
    $originalValue = $user->active;

    $active = request('active');


    if ($active != $originalValue) {
        request('active') ? $user->activeUser() : $user->inactiveUser();
    }
    $user->update($this->validateRequest());

    return redirect('admin/users');
Activity icon

Replied to Two Checkboxes On The Same Form Don't Work.

When I do that, it passes "salary" as the value, which doesn't work. I need a 0 or 1.

Activity icon

Replied to Checkbox

Unfortunately, that didn't fix it. I am still not getting a value passed for the salary checkbox. The form data shows active: 1, but salary is empty.

Activity icon

Replied to Two Checkboxes On The Same Form Don't Work.

Here is the full form code:

@csrf @method('PATCH')
                    <div
                        class="form-group">
                        <label
                            class="pr-4">
                            Employee
                            Number
                        </label>

                        <input
                            type="number"
                            name="employee_num"
                            id="employee_num"
                            class="shadow mt-5 w-1/6"
                            value="{{ $user->employee_num }}"
                        >

                    </div>


                    <div>

                        <label
                            class="pr-4">
                            First
                            Name
                        </label>

                        <input
                            type="text"
                            name="name"
                            id="name"
                            class="shadow mt-5 pl-4"
                            value="{{ $user->name }}"
                        >

                    </div>

                    <div>

                        <label
                            class="pr-4">
                            Last
                            Name
                        </label>

                        <input
                            type="text"
                            name="last_name"
                            id="last_name"
                            class="shadow mt-5 pl-4"
                            value="{{ $user->last_name }}"
                        >

                    </div>


                    <div
                        class="form-group">
                        <label
                            class="pr-4">
                            Initials
                        </label>


                        <input
                            type="initials"
                            name="initials"
                            id="initials"
                            class="shadow mt-5 pl-4"
                            value="{{ $user->initials }}"
                        >
                    </div>


                    <div
                        class="form-group">
                        <label
                            class="pr-4">
                            Email
                        </label>


                        <input
                            type="email"
                            name="email"
                            id="email"
                            class="shadow my-5 pl-4"
                            value="{{ $user->email }}"
                        >
                    </div>

                    <div
                        class="flex w-1/2 mx-auto items-center">
                        <div
                            class="mr-1 text-sm">
                            Avatar
                            Color
                        </div>
                        <div
                            id="Myelement"
                            class=""
                            onclick="changeColor()">

                        </div>
                        <input
                            name="color"
                            type="color"
                            id="color"
                            value="{{ $user->color }}"

                        />
                        @error('color')
                        <span
                            class="invalid-feedback"
                            role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                        @enderror


                        <div
                            class="mr-1 text-sm">
                            Font
                            Color

                            <select
                                name="font_color"
                                class="shadow">

                                @foreach($font_colors as $font_color)

                                    <option
                                        value="{{ $font_color }}"
                                        @if($user->font_color === $font_color) selected @endif>
                                        {{ $font_color }}
                                    </option>

                                @endforeach

                            </select>


                        </div>


                    </div>
                    <div
                        class="flex w-full mx-auto items-center justify-center">

                        <div
                            class="form-group">

                            <label
                                class="pr-2">
                                Salary?
                            </label>


                            <input
                                type="checkbox"
                                name="salary"
                                id="salary"
                                class="shadow my-5"
                                {{ $user->salary ? 'checked' : '' }}
                                value="{{ $user->salary }}"
                            >
                        </div>


                        <div
                            class="form-group">
                            <label
                                class="pr-2 pl-8">
                                Active
                                User
                            </label>


                            <input
                                type="checkbox"
                                name="active"
                                id="active"
                                class="shadow my-5"
                                {{ $user->active ? 'checked' : '' }}
                                value="{{ $user->active }}"
                            >
                        </div>
                    </div>

                    <div
                        class="form-group">

                        <div
                            name="department">
                            Departments:
                            @foreach($user->departments as $dept)
                                <div
                                    class="text-sm">
                                    {{ $dept->name }}
                                </div>
                            @endforeach

                        </div>
                    </div>


                    <div
                        class="mt-5">
                        <a href="/admin/users"
                           class="text-sm text-gray-600 hover:opacity-50">Cancel</a>

                        <button
                            class="button-blue ml-2">
                            Update
                            User
                        </button>
                    </div>
                    @include('errors')
                </form>
Activity icon

Replied to Two Checkboxes On The Same Form Don't Work.

I am using 0 for false and 1 for true.

The strange part is that the form works just fine when only one checkbox is included.

Here is the controller code.

    $user->update($this->validateRequest());

    //original value of checkbox
    $originalSalaryValue = $user->salary;

    $salary = request('salary');
    

    if ($salary != $originalSalaryValue) {
        request('salary') ? $user->salary() : $user->notSalary();
    }


    //original value of checkbox
    $originalValue = $user->active;

    $active = request('active');


    if ($active != $originalValue) {
        request('active') ? $user->activeUser() : $user->inactiveUser();
    }


    return redirect('admin/users');ure I'm duplicating code, but not certain how to reduce it:
Activity icon

Replied to Two Checkboxes On The Same Form Don't Work.

Method was not checked and that is why I didn't see POST. It turns out to be the same thing though. They maintain their original checkbox state when I submit.

Jul
06
4 weeks ago
Activity icon

Replied to Two Checkboxes On The Same Form Don't Work.

If it's supposed to be in the Name column, it's not showing up. The other columns I see are Status, Type, Initiator, Size and Time.

I did test that it was working. I changed data in another field and it did save.

Is Firefox better for this kind of debugging?

Activity icon

Replied to Two Checkboxes On The Same Form Don't Work.

Using Chrome, I'm looking in the Name column. I don't have an entry for POST, but I have one for Update. When I click on that, it says "failed to load response data". However, if I check the Headers, I do see the form data. It says they are both zero, which is the current state they have in the database, despite that I just checked both.

Activity icon

Replied to Two Checkboxes On The Same Form Don't Work.

Great the troubleshooting tips! I suspect I'll learn more as I go.

The source does indeed show both checkboxes. I tried checking both and in the source the Salary is still showing a value of zero, even though it's checked.

Both have different names.

On the Network tab, I'm not sure what I'm looking for. Is it easy to tell me or is there a tutorial/info you can point me to?