chrisgrim

chrisgrim

Member Since 1 Year Ago

Petaluma

at Self Employed

Experience Points 20,600
Experience Level 5

4,400 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 Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

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

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

21 Jun
5 days ago
19 Jun
1 week ago

chrisgrim left a reply on Looking For A Good Laravel Providers Tutorial

I am storing it in a database and it is being pulled into one blade file. What is a model accessor?

chrisgrim left a reply on Looking For A Good Laravel Providers Tutorial

I am creating this for someone who is creating the content for the site using TinyMCE so yes, it is data. To give more info I have actually created a redirect system where whenever my partner creates a link '<a href='/out/{variable name}' it checks my database for the variable name and returns a redirect to a url that matches.

Route::GET('/out/{redirect}', '[email protected]');

then in my controller

public function show(redirect $redirect)
    {
        $newUrl = $redirect->external;
        $test = $redirect->newpage;
        $id = $redirect->id;

        $stat = RedirectStatistic::create([
            'redirect_id' => $id,
        ]);
        
        if($test == true) {
            session()->flash('newurl', $newUrl);
            return redirect()->back();
        } else {
            return back();
        }
    }

The issue I am having is I am using javascript to do a new tab but it keeps getting blocked by popup blockers. So what I was going to try and do instead is every time a view is called have something search through it (like a shortcode does) and replace

 '<a href='/out/'

with

 '<a target="_blank" href='/out/'
18 Jun
1 week ago

chrisgrim started a new conversation Looking For A Good Laravel Providers Tutorial

Hi, I am looking to create a simple provider? that will look through my blade file every time its called and replace '<a href=' with '<a target="_blank" href='

Thanks Chris

17 Jun
1 week ago

chrisgrim started a new conversation How To Use {{config('app.name')}} With [email protected]

Hi, I am trying to do a [email protected]{{config('app.name')}}.com but the @ is causing the {{}} to mess up. Is there a way to get around this?

Thanks

13 Jun
1 week ago

chrisgrim left a reply on How To Test Why My View-Composer Isn't Working

That was it! You rock so much.

chrisgrim left a reply on How To Test Why My View-Composer Isn't Working

@snapey Good Call! In my CategoryComposer I added

    public function compose(View $view)
    {
        $allcategories = Category::all();
        dd($allcategories);
        $view->with('allcategories', $allcategories);
    }

and nothing so I am guessing it isn't being called. In my ComposerServiceProvider how would I add dd()? I have tried

    public function boot()
    {
        dd('test');
        View::composer(
            'layouts.nav', 'App\Http\View\Composers\CategoryComposer'
        );
    }

but nothing happens. So does that mean I am doing something wrong with how I am loading it in my providers list inside app.php? The ComposerServiceProvider.php is inside the folder App\Providers\ComposerServiceProvider::class.

chrisgrim left a reply on How To Test Why My View-Composer Isn't Working

I tried switching them with no luck. Here is the latest ComposerServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        View::composer(
            'layouts.nav', 'App\Http\View\Composers\CategoryComposer'
        );
    }
}

chrisgrim left a reply on How To Upload A Mobile Captured Image Into Laravel In Base64 Format?

Often when I can't get my requests through it's because of a mass assignment issue. Try adding protected $guarded = [];

chrisgrim left a reply on How To Upload A Mobile Captured Image Into Laravel In Base64 Format?

In your Model do you have protected $guarded = []; ?

chrisgrim started a new conversation How To Test Why My View-Composer Isn't Working

I believe I have setup my View-Composer correctly as per the instructions on https://laravel.com/docs/5.8/views#view-composers

I created a new ComposerServiceProvider with php artisan make:provider ComposerServiceProvider. In that file I have

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        View::composer(
            'layouts.nav', 'App\Http\View\Composers\CategoryComposer'
        );
    }
}

Then I registered it in my config/app.php

'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
 
        App\Providers\ComposerServiceProvider::class,

    ],

Then in the folder App\Http\View\Composers\ I created a file CategoryComposer.php and in that I have

<?php

namespace App\Http\ViewComposers;

use Illuminate\View\View;
use App\Category;

class CategoryComposer
{
    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $allcategories = Category::all();
        $view->with('allcategories');
    }
}

Finally in my views/layouts/nav.blade.php file I have

                    @foreach($allcategories as $category)
                        <li><a href="/bestof/{{$category->slug}}" class="text-white">{{$category->name}}</a></li>
                    @endforeach

Yet when I try to look at the page I am getting the error "Undefined variable: allcategories

Am I missing something? How do I even test for what I am missing?

chrisgrim started a new conversation Sending Variable To All Blade Views

Hi, I want to add a foreach in my nav bar to cycle through the categories on my site. How would I safely send the $category variable to every page on my site?

Thanks

12 Jun
2 weeks ago

chrisgrim left a reply on SQLSTATE[42S02]: Base Table Or View Not Found: 1146 Table

Oh man I finally figured it out. I had added code to my AppServiceProvider public boot function that was calling on that table to show in each view!

11 Jun
2 weeks ago

chrisgrim started a new conversation SQLSTATE[42S02]: Base Table Or View Not Found: 1146 Table

I have rolled back all my migrations so there is nothing in my table. When I try to do anything with php artisan I am getting the error

In Connection.php line 664:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'highcanary.categories' doesn't exist (SQL: select * from `categories`)


In Connection.php line 326:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'highcanary.categories' doesn't exist

I tried connecting to a new database but still getting the error. I do have the migration file for category

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('slug');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

I have even tried to do adjust the categories.php model to name the table

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
  public $table = "categories";
  protected $guarded = [];
  protected $with = ['roundups'];
    public function getRouteKeyName()
    {
        return 'slug';
    }
    public function roundups()
    {
        return $this->hasMany(Roundup::class);
    }
}

I am stuck and don't know how to move forward. I tried deleting all my routes and I am still getting the error. Thanks so much for any help!

10 Jun
2 weeks ago

chrisgrim started a new conversation Adding Laravel Validation Response To Vee-Validate For Vue

Hi All I have Vee-Validate for Vue working but I am having an issue when it comes to processing laravel validation errors. (one of my form fields is unique and vee-validate seems to be front-side only). I went online and found some code to try and add the laravel validation but it doesn't seem to be working. Here is my App.js file

import VeeValidate from 'vee-validate';
Vue.use(VeeValidate);

Vue.prototype.$setErrorsFromResponse = function(errorResponse) {
    // only allow this function to be run if the validator exists
    if(!this.hasOwnProperty('$validator')) {
        return;
    }
    
    // clear errors
    this.$validator.errors.clear();

    // check if errors exist
    if(!errorResponse.hasOwnProperty('errors')) {
        return;
    }

    let errorFields = Object.keys(errorResponse.errors);

    // insert laravel errors
    errorFields.map(field => {
        let errorString = errorResponse.errors[field].join(', ');
        this.$validator.errors.add({
            field:field,
            msg: errorString
        });        
    });
};

and in my vue component I have

<div class="input-group">
                    <input type="text" class="form-control" name="shortcode" placeholder="Shortcode Name" v-model="shortcodeName" v-validate="'required'">
                </div>
                <span class="text-sm text-danger">{{ errors.first('shortcode') }}</span>


methods: {
        async submitCoupon() {
            if(!await this.$validator.validate()) { return false; }
            
            let data = {
                'couponcode': this.couponCode,
                'couponamount': this.couponAmount,
                'coupon_description': this.couponDescription,
                'coupon_url': this.couponUrl,
                'shortcode': this.shortcodeName
            };
            console.log(data);
            axios.post(`/coupon/${this.post.slug}`, data)
            .then(response => {
                console.log(response)
                //window.location.href = `${this.eventUrl}/expect`;
            })
            .catch(err => {
                this.$setErrorsFromResponse(err.response.data.errors);
                console.log(err.response.data.errors);
            });
        }
    },

The console log(err.response.data.errors) shows

{shortcode: Array(1)}
shortcode: ["The shortcode has already been taken."]

chrisgrim started a new conversation Best Way To Fetch Customer Chosen Results For An Index

Hi, I am not exactly sure the best practice so I figured I'd ask on here. I have a list of posts and my partner wants to be able to edit the order in which they appear. I was thinking I would make a new column which she can add integers to and then in my controller do something like

$post=Post::where('column', '=', 'something')->get()

Is that how you would do it? Is there a better way to allow my partner to arrange the posts in a specific order instead of just desc from the last added?

Thanks

chrisgrim started a new conversation Issue Returning String And Data With Laravel Shortcode Plugin

Hi, I setup a laravel shortcode plugin using https://github.com/webwizo/laravel-shortcodes. I got everything to work great but I am getting stuck right at the end. I am trying to have it so my friend can enter [coupon] uniqueword [/coupon] and it will return a shortcut with data for that coupon. I have it almost working but I am getting an error when I try to pass the info back into the blade file. Here is my shortcode php file.

  public function register($shortcode, $content, $compiler, $name, $viewData)
  {
    $response = Coupon::where('shortcode', '=', $content)->first();
    return sprintf(`Hi There! Here is ${$response->couponcode} for you!`, $shortcode->class, $content);
  }

I am searching my database for the content(uniqueword) she entered and then getting that object. It works great except when I try to pass it back to the view I get

"Undefined variable: Coupon100 (View: /Users/Chris/code/highcanary/resources/views/posts/page.blade.php)"

Coupon100 is the correct for $response->couponcode but I am guessing the ${} are what is causing the issue when it replaces [coupon]uniqueword[/coupon] in my blade file.

Is there a way to print the data in my controller or should I try to send it down with the return? Thanks so much

09 Jun
2 weeks ago

chrisgrim left a reply on Adding Shortcode Abilities To Laravel Project

Nm I think something else was causing it! It works thanks!

chrisgrim left a reply on Adding Shortcode Abilities To Laravel Project

Hi @bobbybouwmann

Thanks so much that is a cool plugin! I do have one question that maybe you might know a solution. I am using TinyMCE which saves marked up html to my database, then I use {!! content !!} to display it. When I use the laravel shortcode [b class="bold"]Bold text[/b] anywhere in the blade file it works. However, any content she has saved with TinyMCE doesn't work. I think because she is saving the same thing in the database it isn't being computed by the plugin.

I'm not sure what to do about this

chrisgrim started a new conversation Adding Shortcode Abilities To Laravel Project

Hi, I am creating a site for a friend who can't do much programming but likes to be able to write their own posts. I have setup tinyMCE for her but now she wants to be able to add shortcodes like she did in wordpress. She wants to be able to create a shortcode like [test] and save the resulting string content herself.

I understand how to use /{variable} in routes but this isn't really a route. It is something that should run every page load similar to a middleware. I have tried creating middleware to achieve this but I can't see to get it to work.

I'd love advice for the best way to setup a shortcode system like wordpress. Thanks!

08 Jun
2 weeks ago

chrisgrim left a reply on Using Controller To Open New Window For Redirect

I figured it out! in my controller I have

    public function show(redirect $redirect)
    {
        $newUrl = $redirect->external;
        session()->flash('newurl', $newUrl);
        return redirect()->back();
    }

Then in my blade file I have

@if (session()->has('newurl'))
    <redirect-user :newurl="'{{ session('newurl') }}'"></redirect-user>
@endif

And in my vue redirect-user file I have

    beforeMount(){
        window.open(this.newurl, "_blank");
    },

It works great!

07 Jun
2 weeks ago

chrisgrim left a reply on Using Controller To Open New Window For Redirect

I have it setup so my friend doesn't need to edit any html using tinymce. I wouldn't be able to teach her to add a span like that. She has the ability to add a link using tinymce so I am stuck with /out/{whatever}. Is there a way that I can tell Vue to watch for any routes with /out/{whatever} and intercept them?

chrisgrim left a reply on Using Controller To Open New Window For Redirect

@mushood I am creating this site for a friend and she wants to just add a link to text with /out/whatever How would I set this up in Vue? I have been using Vue for a couple of months so I have a moderate understanding.

06 Jun
2 weeks ago

chrisgrim started a new conversation Using Controller To Open New Window For Redirect

Hi, I am creating my own redirect for my website. I was able to get it working using the code below. However I am now on the mission to have it open the redirected page in a new window. I know that I will need to use JS in the view to accomplish this but I am struggling just getting data back into my view.

Here is how I have it

My controller

    public function store(Request $request)
    {
        $request->validate([
        'internal' => 'required|unique:redirects|',
        ]);
        Redirect::create([
            'internal' => request('internal'),
            'external' => request('external'),
        ]);

        return back();
    }
    public function show(redirect $redirect)
    {
        $temp = $redirect->external;
        return redirect($temp);
    }

In my redirect.php I have

    public function getRouteKeyName()
    {
        return 'internal';
    }

and in my routes I do

Route::GET('/out/{redirect}', '[email protected]')->name('redirect-link');

I think I need to adjust my public function show() to look something like this

 public function show(redirect $redirect)
    {
        $temp = $redirect->external;
        
       return redirect()->back()->with('temp');

    }

Then in the blade file have JS that is watching for a temp variable and then create a new blank window with that variables url. Is this how you would go about this or am I making this the wrong way? If so, how would I setup the redirect with data and the JS? I have tried sending data back but have had no luck. I am not that experienced in JS (more in vue) so I don't know how to watch for the variable and create a new window with the url.

03 Jun
3 weeks ago

chrisgrim left a reply on Struggling With Export Paths For Npm

I installed NVM node.js through curl because I couldn't get the brew version to install. And it does actually work I just can't figure out how to get the alias shortcut to work. I tried that medium you sent over but the tips didn't work and I am hesitant to completely uninstall and reinstall.

02 Jun
3 weeks ago

chrisgrim started a new conversation Struggling With Export Paths For Npm

Hi All, I am struggling to get my export paths working on my mac and I was hoping someone here might have an answer. When I am in my laravel project directory and try to run any npm command I get a bash command not found error. However, if I run

source ~/.nvm/nvm.sh

the commands will work as long as I keep that terminal window open. Once I close that window I have to re-run the command to get npm to run again.

I know this has to do with paths but I am still a bit confused by how the paths work. I have three files which I think one of them is causing the issue. The first is my .profile in my local which has

export PATH=/usr/local/bin:/usr/local/sbin:$PATH
source /usr/local/opt/nvm/nvm.sh

The second file I have is .bash_profile in which I have


alias gits="git status"
alias gita="git add"
alias gitc="git commit -v"
export PATH="/usr/local/sbin:/usr/local/bin:/usr/local/opt/nvm/nvm.sh:$PATH"
export PATH="$PATH:~/.composer/vendor/bin"

the third file is my .bachrc which has


alias gits="git status"

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

Thanks so much!

25 May
1 month ago

chrisgrim left a reply on Cleaner Way To Write My Save Image Code?

Oh nice! That is great to see it laid out like this.

chrisgrim started a new conversation Cleaner Way To Write My Save Image Code?

Hi, When I am storing an image my code gets pretty icky. I have moved it to the model from the controller but even then it seems wordy and non-simple. I was wondering if anyone had their own code for storing and image that was simple and pretty.

    public function saveFile($request)
    {
        $title = str_slug(request('title'));
        $extension = $request->file('header-image')->getClientOriginalExtension();
        $filename = $title.'.'.$extension;
        $request->file('header-image')->storeAs('/public/postimages', $filename);
        $large = storage_path().'/app/public/postimages/'.$filename;
        $small = storage_path().'/app/public/thumbimages/'.'thumb'.'-'.$filename;
        Image::make($large)->resize(1200, null, function ($constraint) {
                $constraint->aspectRatio();
            })->save($large)->resize(600, null, function ($constraint) {
                $constraint->aspectRatio();
            })->save($small);
        $post = Post::create([
            'post_image_path' => 'postimages/' . $filename,
            'thumb_image_path' => 'thumbimages/'.'thumb'.'-'.$filename,
        ]);
        return redirect('/');
    }
22 May
1 month ago

chrisgrim started a new conversation In Forms Checking For Old Value Or Using Variable

Hi, I have a update form and I am trying to figure something out. I am already populating the update form value with

value="{{$post->title}}"

However, I would love to combine that with

value="{{ old('title') }}"

I tried

value="{{ old('title') or $post->title }}"

but all I get is the number 1.

How do I display the variable data, but if the form submission gets a validation error, then show the old('title') that they just entered?

Thanks!

chrisgrim left a reply on Validation Request Question

I tried that but it let it go through on both create and update without catching there was no header-image.

chrisgrim started a new conversation Validation Request Question

Hi,

I created a request controller to check a form submission. I am using the same request for both the store and update. The issue I am having is I want to require an image for the create, but not for the update. I have tried this in my request controller

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PostStoreRequest 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 [
            'title' => 'required|unique:posts,id'.$this->id,
            'content' => 'required',
            'seo_meta' => 'required',
            'header-image' => Rule::requiredIf(function () use ($this) {
                return $this->post_image_path == null;
            }),
        ];
    }
}

but I am getting the error back "Cannot use $this as lexical variable"

14 May
1 month ago

chrisgrim left a reply on Working With Pagination And Infinite Loading

Hi @maverickchan

So you don't pass any variable props to the component? Instead you get the json by axios?

13 May
1 month ago

chrisgrim started a new conversation Working With Pagination And Infinite Loading

Hi, I am trying to setup infinite loading in my Vue component. I realized that I needed to combine pagination with the infinite loading so it knows where to stop and start with pulling in more events as the user scrolls. I added pagination and immediately hit an issue. Pagination no longer just sends the events like get() does. When I do a return of $events with pagination I get

{
"current_page": 1,
"data": [],
"first_page_url": "http://showbelow.test?page=1",
"from": 1,
"last_page": 2,
"last_page_url": "http://showbelow.test?page=2",
"next_page_url": "http://showbelow.test?page=2",
"path": "http://showbelow.test",
"per_page": 4,
"prev_page_url": null,
"to": 4,
"total": 8
}

I am pulling event in like this <event-listing :events="{{$events}}"></event-listing> but that no longer works. I am sort of stuck. Do I need to send the data as JSON? Here is my vue component file for event-listing

<template>
    <div>
        <a v-if="isGuest" class="btn" href="/login">Please login</a>
        <div v-if="isLoggedIn">
            <button @click="setUserEmail(`updated-${loggedInUser.email}`)"> Update Email </button>
            <div>user email : {{ loggedInUser.email }}</div>
        </div>  
        <h2>Our Latest Events</h2>
        <div id="app">
            <div id="grid-section">
                <div>
                    <multiselect 
                    v-model="value" 
                    placeholder="Filter by name"
                    label="eventTitle" 
                    track-by="eventTitle" 
                    deselectLabel=''
                    @keyup="filteredEvents"
                    :allow-empty="false"  
                    :options="searchOptions" 
                    >
                    </multiselect>
                </div>
                <div>
                    <input type="text" placeholder="Filter by Price">
                    <button>Go</button>
                </div>
                <div>
                     <div class="datepicker-trigger">
                      <input
                        type="text"
                        id="datepicker-trigger"
                        placeholder="Select dates"
                        :value="formatDates(dateOne, dateTwo)"
                      >

                      <AirbnbStyleDatepicker
                        :trigger-element-id="'datepicker-trigger'"
                        :mode="'range'"
                        :fullscreen-mobile="true"
                        :date-one="dateOne"
                        :date-two="dateTwo"
                        @date-one-selected="val => { dateOne = val }"
                        @date-two-selected="val => { dateTwo = val }"
                      />
                    </div>
                </div>
            </div>
            
            <div id="grid-section">
                <div v-for="event in filteredEvents">
                    <event-listing-item :user="user" :event="event"></event-listing-item>
                </div>
            </div>
            <div id="grid-section">
                <div v-for="event in list">
                    <event-listing-item :user="user" :event="event"></event-listing-item>
                </div>
                <infinite-loading @infinite="infiniteHandler"></infinite-loading>
            </div>
        </div>
    </div>
</template>

<script>
    import _ from 'lodash';
    import Multiselect from 'vue-multiselect';
    import format from 'date-fns/format';
    import usersMixin from '../../mixins/users.js';
    import InfiniteLoading from 'vue-infinite-loading';

    const api = '//hn.algolia.com/api/v1/search_by_date?tags=story';

    export default {
        props: {
            events: { type:Array },
            user: { type:Object },
        },

        mixins: [
            usersMixin,
        ],

        components: {
            Multiselect,
            InfiniteLoading,
        },

        data() {
            return {
                allEvents: this.events,
                value: '',
                searchOptions: this.events,
                 dateFormat: 'D MMM',
                dateOne: '',
                dateTwo: '',
                list: [],
            }
        },

        computed: {
            filteredEvents(){
                if( !this.value ) {return this.allEvents;}
                    const search = this.value.eventTitle.toLowerCase().trim();
                    return this.events.filter(c => c.eventTitle.toLowerCase().indexOf(search) > -1);
            }
        },

        methods: {

            initializeEventObject() {
                return {
                    id: '',
                    eventTitle: '',
                }
            },

            infiniteHandler($state) {
                    const data = this.events;
                    if (data) {
                      this.list = this.list.concat(data);
                      $state.loaded();
                    } else {
                      $state.complete();
                    };
            },

            formatDates(dateOne, dateTwo) {
                let formattedDates = ''
                if (dateOne) {
                    formattedDates = format(dateOne, this.dateFormat)
                }
                if (dateTwo) {
                    formattedDates += ' - ' + format(dateTwo, this.dateFormat)
                }
                    return formattedDates
            },

        }
    };
</script>

Thanks

chrisgrim started a new conversation Origin 'site.name' Has Been Blocked By CORS Policy:

I am trying to setup infinite scrolling with this tutorial https://jsfiddle.net/PeachScript/a4Lxbf9w/

However I am getting an issue with CORS. I get the error

Access to XMLHttpRequest at 'http://hn.algolia.com/api/v1/search_by_date?tags=story&page=1' from origin 'http://showbelow.test' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

I tried adding Access-Control-Allow-Origin to my method but I am still getting the error.

infiniteHandler($state) {
                axios.get(api, {
                    headers: {
                          'Access-Control-Allow-Origin': '*',
                        },
                    params: {
                        page: this.page,
                    },
                }).then(({ data }) => {
                    if (data.hits.length) {
                        this.page += 1;
                        this.list.push(...data.hits);
                        $state.loaded();
                    } else {
                        $state.complete();
                    }
                });
            },
10 May
1 month ago

chrisgrim left a reply on How To Pass User Info Into Vue

@nasmed This is great! Thank you so much for all the info!!! That is a really good suggestion about the users data being visible.

09 May
1 month ago

chrisgrim left a reply on How To Pass User Info Into Vue

I understand that. I am trying to understand if there is a workflow if I want to use @guest and @auth inside a vue component.

chrisgrim started a new conversation How To Pass User Info Into Vue

Hi, In my Blade file I was using @guest and @auth to show certain divs that guests or users could see. I am transfering the work I have done over to Vue and I am wondering what to do about this? If I try to pass

:user="{{ auth()->user() }}

to my component I can get it working, but that breaks the moment there isn't an auth user. I get an error for trying to v:bind empty data. Is there an easy way to get the same @guest and @auth in Vue as I had in the blade file?

Thanks so much

07 May
1 month ago

chrisgrim left a reply on Struggling With Image Submission From Vue To Laravel

Hi @wilk_randall

You were right. It seems like I can only post. Thanks!

06 May
1 month ago

chrisgrim left a reply on Struggling With Image Submission From Vue To Laravel

When I look at the first tutorial everything he talks about with base64 images only seems to focus around the validation, not the actual storing of the file. I am not validating anything at all so shouldn't it work?

I tried changing up my code based on the second tutorial to look like this

createImage() {
            let data = new FormData();
            data.append('eventImage', this.eventImage);
            const config = {
                    headers: { 'content-type': 'multipart/form-data' }
                }

            console.log(this.eventImage);

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

but I am still getting a response that there was no file.

chrisgrim started a new conversation Struggling With Image Submission From Vue To Laravel

I am trying to submit an image from vue to laravel but having an issue. In my Vue file I have

createImage() {
            let data = new FormData();
            data.append('eventImage', this.eventImage);
            let headers = {'Content-Type': 'application/x-www-form-urlencoded'};

            console.log(this.eventImage);

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

When I run the createImage() method the console.log shows this so I know I have a file

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAAAAAAAD/4QBaRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAGXKADAAQAAAABAAAEOAAAAAAAAP/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//AABEIBDgGXAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/3QAEAGb/2gAMAwEAAhEDEQA/APyg2gqfz/Sn9+Rz70wAKOmSeMGlXj5sGvsz82YDcT1A+lABI459aBwcn8Mf0p46hB+ANBLGBSMFjnnr2p3Q7gMYHUUuDgNmnYwCKBXGYwB78nvSgZG0jPqaTBxz0FL8vp6e1AXAKQOByB0 and so on

Then in my controller I have

public function storeImages(Request $request, Event $event)
    {
        if ($request->hasFile('eventImage')) {
            return response()->json(['success' => 'Has File']);
        } else {
            return response()->json(['failed' => 'No File']);
        }
    }

So far, no matter what I do when I submit I get the response failed:No File. In my event.php class I have

 protected $fillable = [
         'eventImage',

    ];

Am I missing something? I can see the file in the console log right before it is submitted, but my controller is telling me that it does not have the file 'eventImage'.

05 May
1 month ago

chrisgrim left a reply on Vue Issue With Submitting A Slug

Amazing, thanks so much for helping me understand responses. I have been trying to get them working for any errors that are generated.

chrisgrim left a reply on Vue Issue With Submitting A Slug

Hi @edoc

I haven't really been able to figure out returned responses. So in my laravel controller I would have

$event->update(request()->validate([
            'eventTitle' => 'required',
        ]) + ['slug'=> str_slug(request('eventTitle'))]);
        return response()->json(compact('slug'));

and then I am not really sure what to do in my Vue file. Something like this?

axios.patch(`${this.eventUrl}/title`, data)
                .then(response => {
                    //then how would I pull the slug from the response here?  
                })

chrisgrim started a new conversation Vue Issue With Submitting A Slug

Hi All,

I am allowing users to change the title of their event which changes the event-slug at the same time. I had the edit form working great in Laravel but I have decided to move everything to Vue components. Now I am getting an issue I can't figure out how to solve.

When I submit the title my controller stores the title and then str_slug(title) to store the slug. The issue I am having is that when I then do a window.location.href after submit it uses the old slug stored in vue instead of using the latest one just created on submit. So I get a 404 error.

<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="floating-label">
                <input type="text" class="floating-input" v-model="eventTitle" placeholder=" " required>
                <label>Title</label>
            </div>
        </div>
        <div class="">
            <button @click.prevent="submitTitle()" class="create"> Next </button>
        </div>
    </div>
</template>

<script>

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

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

        methods: {

            submitTitle() {
                let data = {};
                data.eventTitle = this.eventTitle;

                axios.patch(`${this.eventUrl}/title`, data);
                window.location.href = `${this.eventUrl}/photo`;
            }
        }
    };

</script>

Here is the code I am using. How do I make Vue use my latest event slug as the href?

Thanks!

26 Apr
2 months ago

chrisgrim left a reply on Trouble Understanding How A Vue Plugin Is Working

I tried adding the :key="1" and :key="2" and it did the trick! Thanks so much

25 Apr
2 months ago

chrisgrim left a reply on Trouble Understanding How A Vue Plugin Is Working

Hi All,

@dunsti I have tried adding the render: h=> h(app),

but @maverickchan is right, it isn't needed.

@tomi

How exactly would I add the :key prop? Would I say that it is two different ids?

Thanks Chris

chrisgrim started a new conversation Trouble Understanding How A Vue Plugin Is Working

Hi, I am using the air bnb date picker vue plugin in my project. It works great until I try to have two versions on the same page. I want a user to be able to click to add one date and then click a second date.

Following the instructions I loaded it into my app.js file like so

// import component and stylesheet
import AirbnbStyleDatepicker from 'vue-airbnb-style-datepicker'

import 'vue-airbnb-style-datepicker/dist/vue-airbnb-style-datepicker.min.css'

// make sure we can use it in our components
// see docs for available options
const datepickerOptions = {}

// make sure we can use it in our components
Vue.use(AirbnbStyleDatepicker, datepickerOptions)

I then created a new vue component called create-datepicker and inside there I was able to get it working by using this code

<template>
  <div>
    <div class="datepicker-trigger">
      <input
        type="text"
        id="datepicker-trigger"
        placeholder="Select dates"
        :value="formatDates(dateOne, dateTwo)"
      >

      <AirbnbStyleDatepicker
        :trigger-element-id="'datepicker-trigger'"
        :mode="'range'"
        :fullscreen-mobile="true"
        :date-one="dateOne"
        :date-two="dateTwo"
        @date-one-selected="val => { dateOne = val }"
        @date-two-selected="val => { dateTwo = val }"
      />
    </div>
  </div>
</template>

<script>
import format from 'date-fns/format'

export default {
  data() {
    return {
      dateFormat: 'D MMM',
      dateOne: '',
      dateTwo: ''
    }
  },
  methods: {
    formatDates(dateOne, dateTwo) {
      let formattedDates = ''
      if (dateOne) {
        formattedDates = format(dateOne, this.dateFormat)
      }
      if (dateTwo) {
        formattedDates += ' - ' + format(dateTwo, this.dateFormat)
      }
      return formattedDates
    }
  }
}
</script>

Then I tried to edit the code so I could have two different date pickers like so

<template>
  <div>
    <div class="datepicker-trigger">
        <input
            type="text"
            id="datepicker-trigger"
            placeholder="Select dates"
            :value="formatFirstDate(dateOne)"
        >
        <AirbnbStyleDatepicker
            :trigger-element-id="'datepicker-trigger'"
            :closeAfterSelect="false"
            :mode="'single'"
            :monthsToShow="1"
            :fullscreen-mobile="true"
            :startOpen="true"
            :date-one="dateOne"
            @date-one-selected="val => { dateOne = val }"
        />
    </div>
    <div class="datepicker-trigger">
        <input
            type="text"
            id="datepicker-trigger1"
            placeholder="Select dates"
            :value="formatSecondDate(dateTwo)"
        >
        <AirbnbStyleDatepicker
            :trigger-element-id="'datepicker-trigger1'"
            :closeAfterSelect="false"
            :mode="'single'"
            :monthsToShow="1"
            :fullscreen-mobile="true"
            :startOpen="true"
            :date-two="dateTwo"
            @date-two-selected="val => { dateTwo = val }"
        />
    </div>
    </div>
</template>

<script>
import format from 'date-fns/format'


export default {
  data() {
    return {
      dateFormat: 'D MMM',
      dateOne: '',
      dateTwo: ''
    }
  },
    methods: {
        formatFirstDate(dateOne) {
            let formattedDates = ''
                if (dateOne) {
                    formattedDates = format(dateOne, this.dateFormat)
                } 
            return formattedDates
        },

        formatSecondDate(dateTwo) {
            let formattedDates = ''
                if (dateTwo) {
                    formattedDates = format(dateTwo, this.dateFormat)
                } 
            return formattedDates
        },
    },
}
</script>

It does show two date pickers but when I click on one of them and select a date the other one disappears. How do I make two complete standalone versions?

Thanks!