chrisgrim

chrisgrim

Member Since 1 Year Ago

Petaluma

at Self Employed

Experience Points 21,090
Experience Level 5

3,910 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.

17 Jul
1 day ago
16 Jul
2 days ago

chrisgrim started a new conversation Filtering Through An Array Inside An Foreach

Hi,

I am trying to modify an object "label" inside an array. I am trying to use this code

for (let item of this.dataset) {
                item.label = this.redirected
            }

the problem is this adds the entire "this.redirected" array to each of the item.label so I end up with something like this

0:
backgroundColor: (...)
data: (...)
label: Array(4)
0: "tres"
1: "bes"
2: "xzsx"
3: "xsxscs"

1:
backgroundColor: (...)
data: (...)
label: Array(4)
0: "tres"
1: "bes"
2: "xzsx"
3: "xsxscs"

How would I filter through it so instead I get

0:
backgroundColor: (...)
data: (...)
label: "tres"

1:
backgroundColor: (...)
data: (...)
label: "bes"

Thanks!

11 Jul
1 week ago

chrisgrim left a reply on Htmlspecialchars() Expects Parameter 1 To Be String, Array Given

How would I pass the arrays to my vue component then?

chrisgrim started a new conversation Htmlspecialchars() Expects Parameter 1 To Be String, Array Given

Hi I am getting the error htmlspecialchars() expects parameter 1 to be string, array given. I think its because I have too many levels in my object? If I do a return $stats I get

[
{
"2019-06-27": 0,
"2019-06-28": 0,
"2019-06-29": 0,
"2019-06-30": 0,
"2019-07-01": 0,
"2019-07-02": 1,
"2019-07-03": 0,
"2019-07-04": 0,
"2019-07-05": 0,
"2019-07-06": 0,
"2019-07-07": 0,
"2019-07-08": 0,
"2019-07-09": 0,
"2019-07-10": 0,
"2019-07-11": 0
},
{
"2019-06-27": 0,
"2019-06-28": 0,
"2019-06-29": 0,
"2019-06-30": 0,
"2019-07-01": 1,
"2019-07-02": 0,
"2019-07-03": 0,
"2019-07-04": 0,
"2019-07-05": 0,
"2019-07-06": 0,
"2019-07-07": 0,
"2019-07-08": 0,
"2019-07-09": 0,
"2019-07-10": 0,
"2019-07-11": 0
},
{
"2019-06-27": 0,
"2019-06-28": 0,
"2019-06-29": 0,
"2019-06-30": 0,
"2019-07-01": 2,
"2019-07-02": 0,
"2019-07-03": 0,
"2019-07-04": 0,
"2019-07-05": 0,
"2019-07-06": 0,
"2019-07-07": 0,
"2019-07-08": 0,
"2019-07-09": 0,
"2019-07-10": 0,
"2019-07-11": 0
}
]
I am just trying to send this through to my vue chart with <chart-component :stats="{{$stats}}"></chart-component>

Thanks

chrisgrim left a reply on Filtering Through Array Data In Laravel Controller

Amazing!!! That did it.

Thank you so much

chrisgrim left a reply on Filtering Through Array Data In Laravel Controller

Hi @mstrauss

Thanks for the suggestion! I tried that out like so

        foreach($tests as $test ) {
        //this selects all the dates that a redirect_id is added to redirectstatistic
        $redirects = RedirectStatistic::where('redirect_id', '=', $test)
                ->where( 'created_at', '>=', $dates->keys()->first() )
                ->groupBy( 'date' )
                ->orderBy( 'date' )
                ->get( [
                     DB::raw( 'DATE( created_at ) as date' ),
                     DB::raw( 'COUNT( * ) as "count"' )
                 ] )
                 ->pluck( 'count', 'date' );


    }
        return $redirects;

This returns the filtered last result of the array. How can I have it so $redirects would have an array with 3 results since I have variables in the array?

Thanks!

chrisgrim left a reply on Filtering Through Array Data In Laravel Controller

Hi @jobcerto

If I do that and then return $redirectCalendar I get this

{
"2019-06-11": 0,
"2019-06-12": 0,
"2019-06-13": 0,
"2019-06-14": 0,
"2019-06-15": 0,
"2019-06-16": 0,
"2019-06-17": 0,
"2019-06-18": 0,
"2019-06-19": 0,
"2019-06-20": 0,
"2019-06-21": 0,
"2019-06-22": 0,
"2019-06-23": 0,
"2019-06-24": 0,
"2019-06-25": 0,
"2019-06-26": 0,
"2019-06-27": 0,
"2019-06-28": 0,
"2019-06-29": 0,
"2019-06-30": 0,
"2019-07-01": 3,
"2019-07-02": 1,
"2019-07-03": 0,
"2019-07-04": 0,
"2019-07-05": 0,
"2019-07-06": 0,
"2019-07-07": 0,
"2019-07-08": 0,
"2019-07-09": 0,
"2019-07-10": 0,
"2019-07-11": 0
}

Instead of seperating it into 3 30 days arrays, it just added all the redirect_ids to this one calendar.

chrisgrim started a new conversation Filtering Through Array Data In Laravel Controller

Hey Guys, I am stuck and no matter how much I look around the internet I can't seem to figure out my problem. I have an array of numbers [1,2,3] and I want to filter some code with each of those numbers.

//for this example I am calling this test. But in reality I would get this from ids of my model
        $test = [1,2,3];


        //This creates 30 dates into the past
        $dates = collect();

        foreach( range( -30, 0 ) AS $i ) {
            $date = Carbon::now()->addDays( $i )->format( 'Y-m-d' );
            $dates->put( $date, 0);
        }

        //this selects all the dates that a redirect_id is added to redirectstatistic
        $redirects = RedirectStatistic::where('redirect_id', '=', $test)
                ->where( 'created_at', '>=', $dates->keys()->first() )
                ->groupBy( 'date' )
                ->orderBy( 'date' )
                ->get( [
                     DB::raw( 'DATE( created_at ) as date' ),
                     DB::raw( 'COUNT( * ) as "count"' )
                 ] )
                 ->pluck( 'count', 'date' );


        //this merges those redirect dates with the empty calendar created above
        $redirectCalendar = $dates->merge( $redirects );

You can see in my first where() I am filtering by each number from the array. My ultimate goal would be to have 3 30day calendars where the count only includes for each where the redirect_id is equal to 1, 2, 3.

I hope this makes sense. I am probably doing this the wrong way but I am struggling to figure it out. Thanks so any help

10 Jul
1 week ago

chrisgrim left a reply on Need Help Filtering Through Models In Controller

I tried doing the following

 // Build an array of the dates we want to show, oldest first
        $dates = collect();

        foreach( range( -10, 0 ) AS $i ) {
            $date = Carbon::now()->addDays( $i )->format( 'Y-m-d' );
            $dates->put( $date, 0);
        }
      
        $finalRedirect = collect();

        $tests = redirect::pluck('id');

        foreach($tests as $test) {
        $redirects = RedirectStatistic::whereIn('redirect_id', '=' , $test)
                ->where( 'created_at', '>=', $dates->keys()->first() )
                ->groupBy( 'date' )
                ->orderBy( 'date' )
                ->get( [
                     DB::raw( 'DATE( created_at ) as date' ),
                     DB::raw( 'COUNT( * ) as "count"' )
                 ] )
                 ->pluck( 'count', 'date' );

        

        $finalRedirect = $dates->merge( $redirects );

        }


        return $finalRedirect;

and now I am getting the error: Argument 1 passed to Illuminate\Database\Query\Builder::cleanBindings() must be of the type array, string given, called in

chrisgrim left a reply on Need Help Filtering Through Models In Controller

Hi Snapey, I tried switching the code but I'm still just getting one set of dates. I tried adding a collect() to my $finalRedirect but I can't figure out what foreach I should do so it gives me multiple date ranges for each redirect

        // Build an array of the dates we want to show, oldest first
        $dates = collect();

        foreach( range( -10, 0 ) AS $i ) {
            $date = Carbon::now()->addDays( $i )->format( 'Y-m-d' );
            $dates->put( $date, 0);
        }
      
        $finalRedirect = collect();


        $redirects = RedirectStatistic::whereIn('redirect_id',  redirect::pluck('id'))
                ->where( 'created_at', '>=', $dates->keys()->first() )
                ->groupBy( 'date' )
                ->orderBy( 'date' )
                ->get( [
                     DB::raw( 'DATE( created_at ) as date' ),
                     DB::raw( 'COUNT( * ) as "count"' )
                 ] )
                 ->pluck( 'count', 'date' );


        $finalRedirect = $dates->merge( $redirects );


        return $finalRedirect;
09 Jul
1 week ago

chrisgrim left a reply on Need Help Filtering Through Models In Controller

Hi @mstrauss So I added your code

 $redirects = RedirectStatistic::where( 'created_at', '>=', $dates->keys()->first() )
                 ->whereIn('redirect_id',  $allRedirects->pluck('id')->toArray())
                ->groupBy( 'date' )
                ->orderBy( 'date' )
                ->get( [
                     DB::raw( 'DATE( created_at ) as date' ),
                     DB::raw( 'COUNT( * ) as "count"' )
                 ] )
                 ->pluck( 'count', 'date' );

but it didnt give me what I was looking for. It returned

{
"2019-06-29": 0,
"2019-06-30": 0,
"2019-07-01": 3,
"2019-07-02": 1,
"2019-07-03": 0,
"2019-07-04": 0,
"2019-07-05": 0,
"2019-07-06": 0,
"2019-07-07": 0,
"2019-07-08": 0,
"2019-07-09": 0
}

what I am looking for as a return is

[
{
"2019-06-29": 0,
"2019-06-30": 0,
"2019-07-01": 0,
"2019-07-02": 1,
"2019-07-03": 0,
"2019-07-04": 0,
"2019-07-05": 0,
"2019-07-06": 0,
"2019-07-07": 0,
"2019-07-08": 0,
"2019-07-09": 0
},
{
"2019-06-29": 0,
"2019-06-30": 0,
"2019-07-01": 1,
"2019-07-02": 0,
"2019-07-03": 0,
"2019-07-04": 0,
"2019-07-05": 0,
"2019-07-06": 0,
"2019-07-07": 0,
"2019-07-08": 0,
"2019-07-09": 0
},
{
"2019-06-29": 0,
"2019-06-30": 0,
"2019-07-01": 2,
"2019-07-02": 0,
"2019-07-03": 0,
"2019-07-04": 0,
"2019-07-05": 0,
"2019-07-06": 0,
"2019-07-07": 0,
"2019-07-08": 0,
"2019-07-09": 0
}
]

Where it returns the list of dates with each section being $allRedirect id 1, 2, 3 etc

chrisgrim started a new conversation Need Help Filtering Through Models In Controller

I know I should understand how to do this but the knowledge seems to have left me and I am struggling. I am trying to organize information to send to a chart and I am stuck trying to filter the data. I have multiple $allRedirects and I need to use their ids to filter in the ->where('redirect_id', '=', $allRedirects->id ) later on. How would I do this?

// Get redirect ids
        $allRedirects = redirect::all();

        // Build an array of the dates we want to show, oldest first
        $dates = collect();

        foreach( range( -10, 0 ) AS $i ) {
            $date = Carbon::now()->addDays( $i )->format( 'Y-m-d' );
            $dates->put( $date, 0);
        }


        $redirects = RedirectStatistic::where( 'created_at', '>=', $dates->keys()->first() )
                ->where('redirect_id', '=', $allRedirects->id )
                ->groupBy( 'date' )
                ->orderBy( 'date' )
                ->get( [
                     DB::raw( 'DATE( created_at ) as date' ),
                     DB::raw( 'COUNT( * ) as "count"' )
                 ] )
                 ->pluck( 'count', 'date' );

        $finalRedirect = $dates->merge( $redirects );


        return $finalRedirect;
08 Jul
1 week ago

chrisgrim started a new conversation How To Add Object Elements To Dataset?

Hi, I am trying to add an objects data to a dataset for a chart and I am stuck. I have an object stats console.log(this.stats) =

{2019-07-02: Array(1), 2019-07-01: Array(3)}
2019-07-01: Array(3)
0: {id: 4, redirect_id: 3, created_at: "2019-07-01 03:11:20", updated_at: null}
1: {id: 3, redirect_id: 3, created_at: "2019-07-01 03:11:00", updated_at: null}
2: {id: 1, redirect_id: 2, created_at: "2019-07-01 03:10:33", updated_at: null}
length: 3
__proto__: Array(0)
2019-07-02: Array(1)
0: {id: 2, redirect_id: 1, created_at: "2019-07-02 03:10:46", updated_at: null}
length: 1

Then I have my charts data sets with dummy numbers for now

this.renderChart({
            labels: this.datesArray,
            datasets: [
                {
                    label: 'graph1',
                    backgroundColor: '#FC2525',
                    data: [15, 20]
                },
                {
                    label: 'graph2',
                    backgroundColor: 'Green',
                    data: [23, 40]
                }
            ]
        }, {responsive: true, maintainAspectRatio: false})
    }

How would I use my stats object to get the response

this.renderChart({
            labels: this.datesArray,
            datasets: [
                {
                    label: 'graph1',
                    backgroundColor: '#FC2525',
                    data: [redirect_id: 3, redirect_id: 3,redirect_id: 2]
                },
                {
                    label: 'graph2',
                    backgroundColor: 'Green',
                    data: [redirect_id: 1]
                }
            ]
        }, {responsive: true, maintainAspectRatio: false})
    }

Thanks so much

chrisgrim left a reply on How To Get Array Titles Out Of An Object

I figured it out

console.log(Object.keys(this.stats));

chrisgrim started a new conversation How To Get Array Titles Out Of An Object

Hi, When I console.log(this.stats) I get

{2019-07-02: Array(1), 2019-07-01: Array(3)}
2019-07-01: (3) [{…}, {…}, {…}, __ob__: Observer]
2019-07-02: [{…}, __ob__: Observer]

I can see that I have an object that has 2 arrays inside of it. I am trying to pass the dates only to my chart.js but I cant figure out how to just get the dates names and not the info inside the array.

How would I get an array like this?

[2019-07-01, 2019-07-02]

Thanks

02 Jul
2 weeks ago

chrisgrim started a new conversation Struggling To Get Data Into VueChart

Hi, I am trying to do a chart for data I am gathering off my website. I am grouping my events by date in my controller using

public function index()
    {
        $stats = RedirectStatistic::latest()->get()
        ->groupBy(function ($stats) {
            return $stats->created_at->toDateString();
        });

        return view('statistics.index',compact('stats'));
    }

If I return this wit json it correctly gives me

{
"2019-07-02": [
{
"id": 2,
"redirect_id": 1,
"created_at": "2019-07-02 03:10:46",
"updated_at": null
}
],
"2019-07-01": [
{
"id": 4,
"redirect_id": 3,
"created_at": "2019-07-01 03:11:20",
"updated_at": null
},
{
"id": 3,
"redirect_id": 3,
"created_at": "2019-07-01 03:11:00",
"updated_at": null
},
{
"id": 1,
"redirect_id": 2,
"created_at": "2019-07-01 03:10:33",
"updated_at": null
}
]
}

So I can see on July 1st redirect 3 had 2 and redirect 2 had 1. I then pass this into my vue component which I setup like this.

<script>
import { Line } from 'vue-chartjs'; 

export default {

    extends:Line,

    props: {
        stats: {
            type:Object
        }
    },


    data() {
        return {
                dates: this.stats,
                dates: '',
                datesArray: '',
        }
    },



    mounted() {

        this.datesArray = Object.keys(this.stats).map(a => this.stats[a])

        this.renderChart({
            labels: this.datesArray,
            datasets: [
                {
                    label: 'money',
                    backgroundColor: '#FC2525',
                    data: [15, 20]
                },
                {
                    label: 'newmoney',
                    backgroundColor: 'Green',
                    data: [23, 40]
                }
            ]
        }, {responsive: true, maintainAspectRatio: false})
    }
}


</script>

I realized quickly that renderChart only accepts arrays, not object collections. So I used

this.datesArray = Object.keys(this.stats).map(a => this.stats[a])

to convert the object to an array. However, when I do this I loose my dates and just get 0,1,2. I feel like I am making this harder than it needs to be to create a chart. I would love some help/suggestions.

Thanks!

21 Jun
3 weeks ago
19 Jun
4 weeks 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 month 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 month 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 month 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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.