chrisgrim

chrisgrim

Member Since 1 Year Ago

Petaluma

at Self Employed

Experience Points 23,190
Experience Level 5

1,810 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 132
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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.

16 Sep
1 day ago

chrisgrim left a reply on How To Tell If Elastic Search With Scout Is Setup Correctly

hi @jlrdw

I created an event with the title work so that when I did

return Event::search('work')->get();

it should return the object. If I do a

return Event::all();

it shows me all of the events. Is that what you mean by known expected results?

chrisgrim started a new conversation How To Tell If Elastic Search With Scout Is Setup Correctly

Hi, I followed this tutorial https://medium.com/@samogorm/basic-search-functionality-with-elasticsearch-laravel-scout-6ac182c99cbf to setup Scout and Elastic Search. I had no errors throughout the entire process but when I try to do a search it returns an empty array. I even created a new model for event named work and then have

    public function search(Request $request)
    {
        return Event::search('work')->get();

    }
}

Yet it returns an empty array. Is there a way to check what models have been imported with php artisan scout:import App\Event? Or to verify that it even worked? Like I said, everything seemed to install perfectly with the tutorial so I can't understand what is going wrong. Here is my event.php model

<?php

namespace App;

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;

class Event extends Model
{
    use Searchable;

my app.php

      Laravel\Scout\ScoutServiceProvider::class,
      ScoutEngines\Elasticsearch\ElasticsearchProvider::class,

My scout.php

  'driver' => env('SCOUT_DRIVER', 'elasticsearch'),

'elasticsearch' => [
        'index' => env('ELASTICSEARCH_INDEX', 'laravel'),
        'hosts' => [
            env('ELASTICSEARCH_HOST', 'http://localhost'),
        ],
    ],

in my .env file

ELASTICSEARCH_INDEX=scout
ELASTICSEARCH_HOST=http://localhost:9200

and when I go to that port I can see elasticsearch is up and running

Thanks!

chrisgrim left a reply on Protected Fillable Not Working With Vue Axios Patch

That did it, though there were a few frustrating things. The only way I was able to tell that the mass assignment was working again is because I was looking for it. Using

 axios.post(`${this.eventUrl}/information`, params, headers)
                .then(response => {
                    console.log(response);
                })
                .catch(errorResponse => {
                   console.log(errorResponse);
                });
            },

I received no mass assignment error. The only way I could tell is that the database wasn't being updated. Then when I added the studentPricing back to the protected it was being updated again.

chrisgrim left a reply on Protected Fillable Not Working With Vue Axios Patch

@mabdullahsari I have tried adding

Information::where('event_id', $event->id)->update($request->except(['_token','_method']));

to my store controller and still it allows me to update the studentPricing column.

chrisgrim left a reply on Protected Fillable Not Working With Vue Axios Patch

Ahh I see Yeah it shows fillable and is missing the studentPricing

fillable: array:9 [▼
    0 => "event_id"
    1 => "websiteUrl"
    2 => "ticketUrl"
    3 => "ageRestriction"
    4 => "generalPricing"
    5 => "militaryPricing"
    6 => "seniorPricing"
    7 => "vipPricing"
    8 => "allOtherPricing"
  ]

chrisgrim left a reply on Protected Fillable Not Working With Vue Axios Patch

Is there a way to do this without Tinker? I am struggling to get tinker working and I don't want to waste your time.

chrisgrim left a reply on Protected Fillable Not Working With Vue Axios Patch

Hi @cronix I tried to write my vue axios like this

async submitDetails() {

                this.$v.$touch(); 
                if (this.$v.$invalid) { return false; };
                console.log(this.details);

                const params = new FormData();

                const headers = {'Content-Type': 'application/x-www-form-urlencoded'};

                for (var field in this.details) {
                    params.append(field, this.details[field]);
                }

                params.append('_method', 'PATCH');

                axios.post(`${this.eventUrl}/information`, params, headers)
                .then(response => {

                })
                .catch(errorResponse => {
                   
                });
            },

but now I am getting an error

Column not found: 1054 Unknown column '_method' in 'field list'

is that not the correct way to spoof it?

chrisgrim left a reply on Protected Fillable Not Working With Vue Axios Patch

I have actually looked at that github issue before because of the token needing to be excluded from the sent data. However when I switched from posting as html to vue with axios that token issue disappeared and I could just use request->all() again. That is actually part of the reason I decided to check if my protected fillable was still working.

chrisgrim left a reply on Protected Fillable Not Working With Vue Axios Patch

Also when I submit via axios I did a console log of the data and this is what I get

ageRestriction: 12
allOtherPricing: null
generalPricing: "34.34"
militaryPricing: null
seniorPricing: null
studentPricing: "332.34"
ticketUrl: "http://google.com"
vipPricing: null
websiteUrl: "http://google.com"

chrisgrim left a reply on Protected Fillable Not Working With Vue Axios Patch

Hi @snapey Full information.php model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Information extends Model
{
    protected $fillable = [
        'event_id','websiteUrl','ticketUrl','ageRestriction','generalPricing','militaryPricing','seniorPricing','vipPricing','allOtherPricing'
    ];
    public function event() 
    {
        return $this->hasOne(Event::class);
    }
}

Information migration tab

 public function up()
    {
        Schema::create('information', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('event_id');
            $table->string('websiteUrl')->nullable();
            $table->string('ticketUrl')->nullable();
            $table->unsignedInteger('ageRestriction')->nullable();
            $table->decimal('generalPricing', 6, 2)->nullable();
            $table->decimal('studentPricing', 6, 2)->nullable();
            $table->decimal('militaryPricing', 6, 2)->nullable();
            $table->decimal('seniorPricing', 6, 2)->nullable();
            $table->decimal('vipPricing', 6, 2)->nullable();
            $table->string('allOtherPricing')->nullable();

            $table->timestamps();
        });
    }

Information controller

<?php

namespace App\Http\Controllers;

use App\Information;
use App\Event;
use Illuminate\Http\Request;
use App\Http\Requests\InformationStoreRequest;

class InformationController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Event $event)
    {
        $event->load('information');

        return view('create.information', compact('event'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(InformationStoreRequest $request, Event $event)
    {
        // $event->information()->update($request->all());
        Information::where('event_id', $event->id)->update($request->all());
    }
    /**
     * Display the specified resource.
     *
     * @param  \App\Information  $information
     * @return \Illuminate\Http\Response
     */
    public function show(Information $information)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Information  $information
     * @return \Illuminate\Http\Response
     */
    public function edit(Information $information)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Information  $information
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Information $information)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Information  $information
     * @return \Illuminate\Http\Response
     */
    public function destroy(Information $information)
    {
        //
    }
}

sorry if this is a lot of data

chrisgrim left a reply on Protected Fillable Not Working With Vue Axios Patch

Yeah. I am able to update the studentPricing column in my informations table with a request using axios Patch even though I have removed the studentPricing from my fillable array in my information.php model.

chrisgrim left a reply on Protected Fillable Not Working With Vue Axios Patch

Hmm I tried entered this

Information::where('event_id', $event->id)->update($request->all());

and I tried clearing my cache with php artisan cache:clear and I am still able to update after I have removed it from the protected fillable area.

chrisgrim started a new conversation Protected Fillable Not Working With Vue Axios Patch

Hi, I am building a form input and everything is working great. However I wanted to test to make sure my protected fillable was still working and I discovered I could post to my model even when I removed from protected fillable. In my information.php model I have

class Information extends Model
{
    protected $fillable = [
        'event_id','websiteUrl','ticketUrl','ageRestriction','generalPricing','militaryPricing','seniorPricing','vipPricing','allOtherPricing'
    ];
    public function event() 
    {
        return $this->hasOne(Event::class);
    }
}

I removed the studentPricing option from the array. However when I patch with Vue

  axios.patch(`${this.eventUrl}/information`, this.details)
                .then(response => {

                })
                .catch(errorResponse => {
                   
                });
            },

it updates my database column student details anyways? Here is my store method on the controller

 public function store(InformationStoreRequest $request, Event $event)
    {
        $event->information()->update($request->all());
    }

Thanks

15 Sep
2 days ago

chrisgrim left a reply on Best Laravel Eloquent Tutorial For Searching

Perfect Thanks so much!

chrisgrim left a reply on Best Laravel Eloquent Tutorial For Searching

@mabdullahsari thanks for the video! That totally made a lot of sense. Is there a good tutorial for setting up Elastic Search with laravel?

chrisgrim started a new conversation Best Laravel Eloquent Tutorial For Searching

Hi, Right now I am using pretty simple code for a search

 public function search(Request $request)
    {
        $searchTerm = $request->keywords;
        $ajaxOrganizers = Organizer::where('name', 'LIKE', "%{$searchTerm}%")->limit(30)->get()->toArray();
        

        return response()->json($ajaxOrganizers);
    }

I had two questions. First, I wanted to make sure this was the fastest and cleanest way to search. Second I was reading this article https://m.dotdev.co/writing-advanced-eloquent-search-query-filters-de8b6c2598db and wondering if it still a good way to do it. (The article was written almost 4 years ago) If not, is there a cleaner way to search a model?

Thanks!

10 Sep
1 week ago

chrisgrim left a reply on Understanding Const Inside And Outside Of Vue Component

I actually just solved this after a day of not getting it. I still don't really understand Const but I just used a function

Title: {
                required,
                serverFailed : function(){ return !this.hasServerError('title'); },
            },

and a method

            hasServerError(field) {
                return (field && _.has(this, 'serverErrors.' + field) && !_.isEmpty(this.serverErrors[field]));
            },

and in my data I have

data() {
            return {
                Title: this.event.eventTitle,
                eventUrl:_.has(this.event, 'slug') ? `/create-event/${this.event.slug}` : null,
                serverErrors: [],
                titleActive: false,
            }
        },

where I fill the serverErrors with the error response from the server.

chrisgrim started a new conversation Understanding Const Inside And Outside Of Vue Component

Hi, I am struggling to understand some of the Vue basics, I am learning JS after learning php. I am setting up server validation with vuelidate and running into an issue. I have followed some tutorials online to understand custom validation and I am struggling to get those to work for what I need. I have setup this component file

<template>
    <div>
        <div class="create-guide-title">
        <h2> What is the Title of your Event?</h2>
        </div>
        <div>
            <p>Make it a good one!</p>
        </div>
        <div class="floating-form">
            
            <div class="create-field">
                
                <label>Title</label>
                <input 
                type="text" 
                class="create-input"
                v-model="Title" 
                placeholder=" "
                @input="$v.Title.$touch()"
                 />

                 <div v-if="$v.Title.$error" class="validation-error">
                        <p class="error" v-if="!$v.Title.required">The Street Address is required</p>
                        <p class="error" v-if="!$v.Title.TomValidator">Name does not say Tom</p>
                </div>

            </div>
        </div>
        <div class="">
            <button @click.prevent="submitTitle()" class="create"> Next </button>
        </div>
    </div>
</template>

<script>
    
    import { required, minLength } from 'vuelidate/lib/validators';
    import _ from 'lodash';

    const TomValidator = (value, component) => { return value === 'post'; }



    export default {
        props: {
            event: { type:Object },
        },

        data() {
            return {
                Title: this.event.eventTitle,
                eventUrl:_.has(this.event, 'slug') ? `/create-event/${this.event.slug}` : null,
                errors: [],
            }
        },

        methods: {

            hasServerError(field)
            {
                return 'test';
            },

            status(validation) {
              return {
                error: validation.$error,
                dirty: validation.$dirty
              }
            },

            async submitTitle() {

                let data = {};
                data.title = this.Title;

                axios.patch(`${this.eventUrl}/title`, data)
                .then(response => {
                // all is well. move on to the next page
                    console.log(response);
                })
                .catch(error => {
                    console.log(error.response.data.errors);
                    this.errors = error.response.data.errors;

                });
            }
        },

        validations: {
            Title: {
                required,
                TomValidator,
                titleTaken
            },
        },
    };

</script>

The custom Tom validation works and unless they write the name Tom in it will catch. I'm hoping to set it up so that if I get a server error ie title:The title has already been taken. I can add that to the data: errors and check that.

I am having trouble understanding

const TomValidator = (value, component) => { return value === 'post'; }

as it is outside my exported default and I can't figure out how to reference the data.

const titleTaken = (value, component) => {How do I access my returned data}
09 Sep
1 week ago

chrisgrim left a reply on Vue Vuelidate Server Side Error Responses

Hi @sti3bas

I actually tried using Vee-Validate but their latest 3.0 release has been giving me a lot of issues which is a shame because I liked it a lot.

chrisgrim started a new conversation Vue Vuelidate Server Side Error Responses

Hi All, I have been searching the web trying to find tutorials on how to return Laravels server-side errors through Vuelidate. I have Vuelidate errors working great for required however if the user submits and the website field isn't unique I need to show that error. Does anyone use Vuelidate for this and have an example or know of a reference site? Thanks!

chrisgrim left a reply on How To Validate Unique Rules On An Update

Hi @wilk_randall

So I tried adding what you showed me

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class OrganizerUpdateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'website' => ['required',
                            Rule::unique('organizers')
                                  ->ignore($this->website)
                        ],
        ];
    }
}

I am getting an error "Class 'App\Http\Requests\Rule' not found", which tells me that I wrote the code wrong somehow. Even if I use $this->id it gives me the same error.

chrisgrim left a reply on Axios Patch Issue When Updating Model

Gotcha, Thanks so much for all your help and that site!

chrisgrim left a reply on Axios Patch Issue When Updating Model

@wilk_randall Oh I see. I didn't know that was how you had to do it. Is there a pro/con to doing it either way?

chrisgrim started a new conversation How To Validate Unique Rules On An Update

Hi, I am trying to validate my model for uniqueness but I am running into an issue when I try to update. I created a new UpdateRequest.php file.

return [
            'website' => 'required|unique:organizers',
        ];

When I update with my form it gives me the error "website":["The website has already been taken."]}}. I guess this makes sense because in my database there is that website, even though it is on the model I am trying to update. I looked into the laravel docs and from what I can see they only show how to ignore the rule

Forcing A Unique Rule To Ignore A Given ID
'email' => 'unique:users,email_address,10'

I don't want to ignore this rule in the case where I do update the website and it conflicts with another entry. Thanks

chrisgrim left a reply on Axios Patch Issue When Updating Model

I did have PATCH in my routes file. Yet for some reason it still didn't work

chrisgrim left a reply on Axios Patch Issue When Updating Model

Ok I solved it. I just tried it was an axios.post even though I was updating.

axios.post(`${this.eventUrl}/${this.organizer.id}/organizer`, params, headers)

I guess patch wasn't what I wanted after all

chrisgrim left a reply on Axios Patch Issue When Updating Model

I am submitting an image which is my I was using formData. I am not sure what is happening because if I try to create a new model it works fine. Here is more of my code

if ( this.organizer.id == '' ) {
                // post the form data to server
                axios.post(`${this.eventUrl}/organizer`, params, headers)
                .then(response => {
                    // all is well. move on to the next page
                    // window.location.href = `${this.eventUrl}/dates`;
                })
                .catch(errorResponse => {
                    // show if there are server side validation errors
                });
            } else {
                for (var pair of params.entries()) {
                    console.log(pair[0]+ ', ' + pair[1]); 
                };
                // post the form data to server
                axios.patch(`${this.eventUrl}/${this.organizer.id}/organizer`, params, headers)
                .then(response => {
                    // all is well. move on to the next page
                    // window.location.href = `${this.eventUrl}/dates`;
                    console.log(response)
                })
                .catch(errorResponse => {

                    console.log(errorResponse)
                });
            };
        },

When I do an axios post it works fine and creates the new model. It's only the update the doesnt seem to work. I did some more testing as well. In my controller, I was using

$organizer->update($request->all());

However I updated it to

 $organizer->update([
                'slug' => request('name'),
                'name' => request('name'),
                'website' => request('website'),
                'description' => request('description'),
                'user_id' => auth()->id(),
                'imagePath' => request('imagePath'),
            ]);

and I am not getting this error when I submit.

Integrity constraint violation: 1048 Column 'name' cannot be null (SQL: update `organizers` set `name` = ?, `website` = ?, `slug` = ?, `description` = ?, `imagePath` = ?, `organizers`

so it is obviously not sending the data. Yet how come I can see that it is in the formdata? and why does it work when doing a post request?

chrisgrim left a reply on Checking For Google Maps Places Json Data Using If Statement

Hi @skauk

If you look at my code you can see

 initAutocomplete() {
              // Create the autocomplete object, restricting the search predictions to
              // geographical location types.
              autocomplete = new google.maps.places.Autocomplete(
                  document.getElementById('autocomplete'), {types: ['geocode']});

              // Avoid paying for data that you don't need by restricting the set of
              // place fields that are returned to just the address components.
              autocomplete.setFields(['address_component']);

              // When the user selects an address from the drop-down, populate the
              // address fields in the form.
              autocomplete.addListener('place_changed', fillInAddress);
            },

Isnt that function in my code?

I will probably do as you say and go back to the compontent I was using, but I was just seeing if there was a way to save money with google searches by only getting the specific data I need.

chrisgrim started a new conversation Axios Patch Issue When Updating Model

Hi Guys, Im hoping to have a fresh pair of eyes look at this because I can't see what I am doing wrong. I am trying to update a laravel model and I can't seem to make it work. I created the form with html like so

<form method="POST" action="/create-event/{{$event->slug}}/1/organizer" class="floating-form">
            @csrf
            @method('PATCH')
                <input type="text" name="name" placeholder="name">
                <input type="text" name="slug" placeholder="slug">
                <input type="text" name="description" placeholder="description">
                <input type="text" name="imagePath" placeholder="imagePath">
                <input type="text" name="twitterHandle" placeholder="twitterHandle">
                <input type="text" name="facebookHandle" placeholder="facebookHandle">
                <input type="text" name="instagramHandle" placeholder="instagramHandle">
                <input type="text" name="website" placeholder="website">

                <button type="submit" class="create">
                    Create
                </button>
            </form>
            @include('layouts.errors')

In the action url I am using 1 for my organizer model id just to test. This form works great and updates my model. However when I try to do the same thing in Vue I am not getting any errors but it isn't updating my model either. In Vue I have

axios.patch(`${this.eventUrl}/${this.organizer.id}/organizer`, params, headers)
                .then(response => {
                    console.log(response)
                })
                .catch(errorResponse => {
                    console.log(errorResponse)
                });

the params variable is actually formdata but if I use

for (var pair of params.entries()) {
  console.log(pair[0]+ ', ' + pair[1]); 
 };

I get

id, 1
app.js:3101 name, blue rath
app.js:3101 description, xszxzsx
app.js:3101 website, zxzsx
app.js:3101 imagePath, zsxzx
app.js:3101 twitterHandle, null
app.js:3101 facebookHandle, null
app.js:3101 instagramHandle, null
app.js:3101 slug, blue-rath

So it is actually submitting the same data as my html form to the same location. I am not getting any error messages either so I don't really know what to do. Thanks

08 Sep
1 week ago

chrisgrim left a reply on How Specific To Be With My Model Creation?

Oh that is a cool way to do it! Even if I can't catch every single case it still will never have an issue with the same url

chrisgrim left a reply on How Specific To Be With My Model Creation?

Thanks for the quick responses. I will look into both of those things. From what I saw real quick neither of those solutions deals with the problem of 'Dinowars' vs 'Dino Wars'. Would it be worth doing a where() search for LIKE keywords or is that overkill? Thanks

chrisgrim started a new conversation How Specific To Be With My Model Creation?

Hi, I have a more best practices question. I am creating a site where users can create organizers/events and I am running into an interesting question. Normally I would just set up my project so that the name needs to be unique so I can't have Post1 and Post1. However, I'm wondering if that isn't enough for users entering the events. I base my RouteKey off slug and that adds some interesting problems. Suddenly one user can add Post 1 and another can add Post-1 and that passes my validation tests fine but errors out on submission to my database. Also, what if a user adds an event called 'Dinowars' and another enters one called 'Dino Wars'. They are obviously the same event and I don't want them entered twice. How do you deal with this?

06 Sep
1 week ago

chrisgrim left a reply on UpdateOrCreate Need More Help Cleaning Code

Ahh I see what you mean. So just have two functions in my vue file, one that does an axios post to create and one that does an axios patch to the update?

chrisgrim left a reply on UpdateOrCreate Need More Help Cleaning Code

@cometads I am sure that works but I really want to get a solid understanding of how things work and how I would program it myself. @snapey I was just trying to make it simple for the user to create a new organizer or assign the event to a different organizer and have the ability to edit that organizers info at the same time in the same page.

chrisgrim left a reply on UpdateOrCreate Need More Help Cleaning Code

Hi @snapey

I have to admit it's getting a little confusing to me. So what I think I want is a user can create a new organization but it has to have a unique slug. A user can also update an existing organization but if they change the name/slug then that has to be unique as well. If I did something like this

    $organizers = Organizer::updateOrCreate(
            [
                'id' => request('id'),
            ],
            [
                'name' => request('name'),
                'description' => request('description'),
                'user_id' => auth()->id(),
                'imagePath' => request('imagePath'),

            ]
        );

Then they can create a new model or update one from the list of organizers. The only catch is I can't check for the slug being unique because I get the slug from the name. Does this mean I need to create a slug in vue and then pass it to my controller where I can pass it through the OrganizerStoreRequest? I don't think I am actually passing the $organizer through to the store request. I only have a wildcard in my route for the event. I am not sure why I included the $organizer before.

chrisgrim left a reply on UpdateOrCreate Need More Help Cleaning Code

So that would mean I could just do

public function store(OrganizerStoreRequest $request, Event $event, Organizer $organizer)
    {
        if (!$organizer = $organizer->updateOrCreate(
                [
                    'slug' => str_slug(request('title'))
                ],
                [
                    $request->only(['id','title','description'])
                ]
            )) {
            return response()->json(['error' => 'Failed to save organizer'], 402);
        }

chrisgrim started a new conversation UpdateOrCreate Need More Help Cleaning Code

Hi, I just asked a question about cleaning code but I was too premature with my best answer. I am using a updateOrCreate and so I need to write my code this like

public function store(OrganizerStoreRequest $request, Event $event, Organizer $organizer)
    {
        if (!$organizer = $organizer->updateOrCreate(
                [
                    'slug' => str_slug(request('title'))
                ],
                [
                    $request->all() + ['user_id' => auth()->id()]
                ]
            )) {
            return response()->json(['error' => 'Failed to save organizer'], 402);
        }

This doesn't work because of this part I'm sure

$request->all() + ['user_id' => auth()->id()]

but is there a way to write this without listing all of the requests? Thanks!

chrisgrim left a reply on Clean Code For Request->all()

Thanks so much!!

chrisgrim started a new conversation Clean Code For Request->all()

Hi I have this code that I have tried to optimize as much as possible

if (!$organizer = $organizer->updateOrCreate($request->all())) {
            return response()->json(['error' => 'Failed to save organizer'], 402);
        }

The model calls for a slug which normally I would do 'slug' => str_slug(request('title'))

How would I add just this one without having to move away from request all and listing all of my requests?

chrisgrim left a reply on Checking For Google Maps Places Json Data Using If Statement

HI @skauk Thanks for the response! I looked into the example and that took me down a whole different path. I saw immediately that using vue2-google-maps - npm was too restrictive to use the code form the example. For the example I need to call

 <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"
        async defer></script>

while Vue2-google-maps has me use the api key in the app.js file. So I tried using just the example you provided and am having trouble even getting it going. When I put all the code in I am getting this error

initautocomplete is not a function invalidvalueerror

here is my vue file

<template>
    <div class="create-content">
        <div class="create-title">
            <h2> Location</h2>
        </div>
        <div class="create-form locations">
            <div class="location-section-1">
                <div class="create-field">

                    <label>Is The Location Hidden?</label>
                    <multiselect 
                    v-model.trim="location.HiddenLocation" 
                    deselect-label="Can't remove this value" 
                    placeholder="Is the location is being withheld?" 
                    :options="locationOptions" 
                    open-direction="bottom"
                    :searchable="false" 
                    :allow-empty="false"
                    :class="{ active: hiddenActive}"
                    @click="hiddenActive = true"
                    @blur="hiddenActive = false"
                    />

                </div>
                <div class="create-field" v-if="showHiddenLocation">

                    <label> Please enter how participants will be notified </label>
                    <textarea 
                    v-model.trim="location.StreetAddress" 
                    class="create-input area" 
                    rows="8" 
                    :class="{ active: notifiedActive,'error': $v.location.StreetAddress.$error }"
                    placeholder=" " 
                    required 
                    autofocus
                    @click="notifiedActive = true"
                    @blur="notifiedActive = false"
                    @input="$v.location.StreetAddress.$touch"
                    />
                    <div v-if="$v.location.StreetAddress.$error" class="validation-error">
                        <p class="error" v-if="!$v.location.StreetAddress.required">The Street Address is required</p>
                    </div>
                    
                </div>
            </div>
            <div class="location-section-2">
                <div class="create-field">

                    <label v-if="showHiddenLocation"> City  </label>
                    <label v-else="specificLocation"> Street Address </label>
                        
                </div>
            </div>
            <div id="locationField">
              <input id="autocomplete"
                     placeholder="Enter your address"
                     onFocus="geolocate()"
                     type="text"/>
            </div>
            <div class="location-section-3">

                    <div v-if="currentPlace">
                        
                    </div>
                </div>
            </div>
            <div class="location-section-4">
                <div class="create-field">
                    
                    <label>Regions</label>
                    <multiselect 
                    v-model.trim="selectedRegions" 
                    :options="this.regions ? regionOptions : []" 
                    :multiple="true" 
                    placeholder="Select Region. You may select more than one." 
                    track-by="id"
                    open-direction="bottom"
                    required 
                    label="region"
                    @input="$v.selectedRegions.$touch"
                    :class="{ active: hiddenActive,'error': $v.selectedRegions.$error}"
                    @click="hiddenActive = true"
                    @blur="hiddenActive = false"
                    />

                    <div v-if="$v.selectedRegions.$error" class="validation-error">
                        <p class="error" v-if="!$v.selectedRegions.required">Please select at least one Region</p>
                    </div>
                </div>
            </div>
                
            <div class="create-button">
                <button :disabled="$v.$invalid" @click.prevent="submitLocation()" class="create"> Next </button>
            </div>

        </div>
    </div>
</template>

<script>
    import Multiselect from 'vue-multiselect';
    import _ from 'lodash';
    import { required, minLength } from 'vuelidate/lib/validators';

    var placeSearch, autocomplete;

    var componentForm = {
      street_number: 'short_name',
      route: 'long_name',
      locality: 'long_name',
      administrative_area_level_1: 'short_name',
      country: 'long_name',
      postal_code: 'short_name'
    };

    export default {
        props: {
            event: { type:Object },
            regions: { type:Array },
            pivots: { type:Array },
        },

        components: { 
            Multiselect
        },

        computed: {
            showHiddenLocation: function() {
                if( this.location.HiddenLocation === 'Yes' ) { 
                    return '1'; } else { return ''}
            },
        },

        data() {
            return {
                location:this.initializeEventObject(),
                hiddenLocation: 'false',
                regionOptions:this.regions,
                selectedRegions: this.pivots,
                locationOptions: [ 'Yes', 'No' ],
                eventUrl:_.has(this.event, 'slug') ? `/create-event/${this.event.slug}` : null,
                lat: '',
                lon: '',
                name: '',
                locationActive: false,
                notifiedActive: false,
                hiddenActive: false,
                center: { lat: 45.508, lng: -73.587 },
                markers: [],
                places: [],
                currentPlace: null,
                address: ''
            }
        },

        methods: {
            initializeEventObject() {
                return {
                    StreetAddress: '',
                    City: '',
                    State: '',
                    Country: '',
                    Zipcode: '',
                    HiddenLocation: '',
                    Lat: '',
                    Long: '',
                }
            },

            updateEventFields(input) {
                if ((input !== null) && (typeof input === "object") && (input.id !== null)) {
                    this.location = _.pick(input, _.intersection( _.keys(this.location), _.keys(input) ));
                }
            },

            async submitLocation() {

                if (this.$v.$invalid) { return false; }

                axios.get(url)
                .then(response => {
                    this.location.Lat = response.data[0].lat;
                    this.location.Long = response.data[0].lon;
                    let data = this.location;
                    data.Country = this.selectedCountry;
                    data.Region = this.selectedRegions.map(a => a.id);


                    axios.patch(`${this.eventUrl}/location`, data)
                    .then(response => {
                        console.log(response)
                    })
                    .catch(errorResponse => {
                        // show if there are server side validation errors
                        this.validationErrors = errorResponse.response.data.errors
                        console.log(errorResponse.response.data.errors)

                    });
                })
                .catch(errorResponse => {
                // show if there are server side validation errors
                });

            },

            addTag (newTag) {
                const tag = {
                    location: newTag,
                    id: newTag.substring(0, 2) + Math.floor((Math.random() * 10000000))
                }
                this.regionOptions.push(tag)
                this.selectedRegions.push(tag)
            },

            toggle() {
                this.hiddenLocation = !this.hiddenLocation;
            },

            toggleActive(e) {
                this.flags[e.currentTarget.name] = !this.flags[e.currentTarget.name];
            },

            initAutocomplete() {
              // Create the autocomplete object, restricting the search predictions to
              // geographical location types.
              autocomplete = new google.maps.places.Autocomplete(
                  document.getElementById('autocomplete'), {types: ['geocode']});

              // Avoid paying for data that you don't need by restricting the set of
              // place fields that are returned to just the address components.
              autocomplete.setFields(['address_component']);

              // When the user selects an address from the drop-down, populate the
              // address fields in the form.
              autocomplete.addListener('place_changed', fillInAddress);
            },

            fillInAddress() {
              // Get the place details from the autocomplete object.
              var place = autocomplete.getPlace();

              for (var component in componentForm) {
                document.getElementById(component).value = '';
                document.getElementById(component).disabled = false;
              }

              // Get each component of the address from the place details,
              // and then fill-in the corresponding field on the form.
              for (var i = 0; i < place.address_components.length; i++) {
                var addressType = place.address_components[i].types[0];
                if (componentForm[addressType]) {
                  var val = place.address_components[i][componentForm[addressType]];
                  document.getElementById(addressType).value = val;
                }
              }
            },

            // Bias the autocomplete object to the user's geographical location,
            // as supplied by the browser's 'navigator.geolocation' object.
            geolocate() {
              if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                  var geolocation = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                  };
                  var circle = new google.maps.Circle(
                      {center: geolocation, radius: position.coords.accuracy});
                  autocomplete.setBounds(circle.getBounds());
                });
              }
            },
                        

            
        },
    

        mounted() {
            this.updateEventFields(this.event.location);

            if (this.event.location.Country) {
                this.selectedCountry = this.event.location.Country;
            }

            if (this.event.location.HiddenLocation == 1) {
                this.hiddenLocation = 'true';
            }
            if (!this.event.location.HiddenLocation == 1) {
                this.location.HiddenLocation = 'No';
            }




        },

        validations: {
            selectedRegions: {
                required
            },
            location: {
                StreetAddress: {
                   required
                },
                City: {
                   required
                },
                State: {
                    required,
                },
                Zipcode: {
                    required
                },
            },
        },
            
};



</script>

Thanks!

05 Sep
1 week ago

chrisgrim started a new conversation Checking For Google Maps Places Json Data Using If Statement

Hi, I am using google auto complete for my location entry form. I am able to get the data back from google but I am having an issue when I am trying to enter it into my data. Here is my data

data() {
            return {
                location:this.initializeEventObject(),
                center: { lat: 45.508, lng: -73.587 },
                markers: [],
                places: [],
                currentPlace: null,
            }
        },

        methods: {
            initializeEventObject() {
                return {
                    StreetAddress: '',
                    City: '',
                    State: '',
                    Country: '',
                    Zipcode: '',
                    HiddenLocation: '',
                    Lat: '',
                    Long: '',
                }
            },

and after the user enters their info I call

setPlace(place) {   
                    this.location = {
                        StreetAddress: place.address_components[0].long_name + ' ' + place.address_components[1].long_name,
                        City: place.address_components[3].long_name,
                        State: place.address_components[4].long_name,
                        Country: place.address_components[5].long_name,
                        Zipcode: place.address_components[6].long_name,
                        HiddenLocation: '',
                        Lat: place.geometry.location.lat(),
                        Long: place.geometry.location.lng(),
                    }
            },

This works great except if the user doesn't enter a street, instead only adds a city then I get this error

app.js:41532 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'long_name' of undefined"

found in

I tried to do this

if (place.address_components[0].long_name) {
                    this.location = {
                        StreetAddress: place.address_components[0].long_name + ' ' + place.address_components[1].long_name,
                        City: place.address_components[3].long_name,
                        State: place.address_components[4].long_name,
                        Country: place.address_components[5].long_name,
                        Zipcode: place.address_components[6].long_name,
                        HiddenLocation: '',
                        Lat: place.geometry.location.lat(),
                        Long: place.geometry.location.lng(),
                    }
                };

but I am still getting the error. I also have another issue that sometimes place.address_components[5] is Los Angeles or sometimes its Los Angeles County. Is there a better way to uniform the response instead of just using [number]?

Thanks!

04 Sep
1 week ago

chrisgrim left a reply on @click IsActive Selecting All Inputs On Page

Thanks Ill give this a shot!

03 Sep
2 weeks ago

chrisgrim started a new conversation @click IsActive Selecting All Inputs On Page

Hi All, I am trying to do an is active / not active css change on my input fields with vue. I have it working except for one little problem. If I select one field it does the css change for all of my input fields. Here is how I have the code now.

            <div class="create-field">

                <label>City</label>
                <input
                v-model.trim="location.City"
                type="text" 
                class="create-input"
                :class="{ active: isActive,'error': $v.location.City.$error }"
                name="city" 
                placeholder=" "
                @input="$v.location.City.$touch"
                @click="isActive = true"
                @blur="isActive = false"
                />

                <div v-if="$v.location.City.$error" class="validation-error">
                    <p class="error" v-if="!$v.location.City.required">The City is Required</p>
                </div>

            </div>
            <div class="create-field">

                <label>State</label>
                <input 
                v-model.trim="location.State" 
                type="text" 
                class="create-input" 
                :class="{ active: isActive,'error': $v.location.State.$error }"
                name="state" 
                placeholder=" "
                @input="$v.location.State.$touch"
                @click="isActive = true"
                @blur="isActive = false"
                />

                <div v-if="$v.location.State.$error" class="validation-error">
                    <p class="error" v-if="!$v.location.State.required">The State is required</p>
                </div>

            </div>

What is the simplest way to fix this? Thanks!

31 Aug
2 weeks ago
29 Aug
2 weeks ago

chrisgrim started a new conversation What Is The Best Validation For Vue?

Hi, I have been looking into Vee-Validate but I wanted to see if there was a simpler validation for Vue. The latest Vee has a lot of extra code to bring in the rules and I am struggling to get it working with my server validation (checking for unique in the database)

Thanks!

chrisgrim started a new conversation Better Understanding Of Eager Loading

Hi, I have a quick question. In my show method I have

  public function create(Event $event)
    {
return $event
}

Using a wildcard in my url I get the specific event model returned. However if I want to eager load a model with that event I assumed I would use

  public function create(Event $event)
    {

        return $event->with('location')->get();
}

However, that returns all of my events with location eager loaded. How do I just return the individual event with only its locations.

Thanks!

chrisgrim left a reply on Is The Update->request(all) With Token A Recent Thing?

Hi @nakov and @click One last question. So I am starting to understand the returning of the relationship object vs just the result of the relationship. One thing I am having trouble understanding. If I update just the result of the relationship using $event-expectation->update am I losing the mass assignment check for the rest of my fields? I want to make sure my submissions are protected and someone can't submit a user id or event id with the form.

Thanks Chris

chrisgrim left a reply on Is The Update->request(all) With Token A Recent Thing?

Hi Guys Thank you so much for all your answers. That stackoverflow answer is really helping me understand so thank you so much @click. You guys are why I love this site!