Shiva

Member Since 6 Years Ago

Experience Points
22,070
Total
Experience

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

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

  • Community Pillar

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

Level 5
22,070 XP
Jan
11
1 week ago
Activity icon

Replied to Getting My Products To Split Accordingly

It isn't working as I'm expecting. This is what I have

old products

Product 1
Product 2
Product 3
Product 4
Product 5

New products

Product 2
Product 3
Product 4
Product 5

I'm expecting my $contains[] to have

Product 2
Product 3
Product 4
Product 5

and my $doesntContain[] to have

Product 1

Instead what I'm getting is this:

$contains = []

and $doesntContain =

Product 2
Product 3
Product 4
Product 5
Activity icon

Started a new Conversation Getting My Products To Split Accordingly

I'm trying to do a bulk upload of my products. So what I'm trying to do is find out if the new products is the same as the old products. I'm not sure if I'm doing it correctly, because when I hit the true part of my if statement I get an empty array and if I get to the false part of my if statement then I get a product that does exist in my old products.

Here is my code

public function uploadProducts(Category $category, Product $product)
{
    $oldCategory = $category;
    $oldProducts = Product::where('cateogry_id', $oldCategory->id)->get();

    $newCategory = request('category');
    $newProducts = Product::where('cateogry_id', $newCategory->id)->get();

    $contains = [];
    $doesntContain = [];

    foreach($newProducts as $product)
    {
        if($oldProducts->contains($product))
        {
            $contains = $product;
        }else{
            $doesntContain = $product;
        }
    }

    dd($doesntContain);
}
Jan
05
1 week ago
Activity icon

Started a new Conversation Phasor Graph

I need to create a phasor graph and I'm using vue js, I'm not sure where to find package for it. Chart.js and google charts doesn't have it.

Activity icon

Started a new Conversation SELECT List Is Not In GROUP BY Clause And Contains Nonaggregated Column

I'm trying to group my data by date. but I'm getting this error

Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'laravel-site.tech.id' 
which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by 
(SQL: select * from `tech` group by `created_at`)

Here is my code

$table = DB::table('tech')
                    ->select('*')
                    ->groupBy('created_at')
                    ->get();
        dd($table);
Activity icon

Replied to Creating An Annotation Chart

I've added that, but I'm still getting the same 2 errors and another error

ReferenceError: drawChart is not defined
Activity icon

Started a new Conversation Creating An Annotation Chart

I'm trying to create an annotation chart using vue and inertia, but I'm getting these errors in my console.

Error in render: "ReferenceError: google is not defined"

and

ReferenceError: google is not defined

Here is my code

<template>
    <div class="content-wrapper" style="margin-left: 0;">
        <div class="content">
            <div class="container">
                <div class="row pt-5">
                    <div class="col-lg-12">
                        {{ drawChart() }}                       
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import Layout from './Layout'

export default {
    layout: (h, page) => h(Layout, [page]),
    layout: Layout,
    props: {

    },
    data() {
      return {

        }
      }
    },
    methods: {
        drawChart(){
            var data = new google.visualization.DataTable();
            data.addColumn('date', 'Date');
            data.addColumn('number', 'Kepler-22b mission');
            data.addColumn('string', 'Kepler title');
            data.addColumn('string', 'Kepler text');
            data.addColumn('number', 'Gliese 163 mission');
            data.addColumn('string', 'Gliese title');
            data.addColumn('string', 'Gliese text');
            data.addRows([
                [new Date(2314, 2, 15), 12400, undefined, undefined,
                    10645, undefined, undefined],
                [new Date(2314, 2, 16), 24045, 'Lalibertines', 'First encounter',
                    12374, undefined, undefined],
                [new Date(2314, 2, 17), 35022, 'Lalibertines', 'They are very tall',
                    15766, 'Gallantors', 'First Encounter'],
                [new Date(2314, 2, 18), 12284, 'Lalibertines', 'Attack on our crew!',
                    34334, 'Gallantors', 'Statement of shared principles'],
                [new Date(2314, 2, 19), 8476, 'Lalibertines', 'Heavy casualties',
                    66467, 'Gallantors', 'Mysteries revealed'],
                [new Date(2314, 2, 20), 0, 'Lalibertines', 'All crew lost',
                    79463, 'Gallantors', 'Omniscience achieved']
            ]);

            this.annotationData = data;
            var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));

            var options = {
                displayAnnotations: true
            };

            chart.draw(data, options);
        }
    }
}
</script>
Dec
22
3 weeks ago
Activity icon

Replied to Getting My Query To Get The Total Amount

If I do that I get this error

Grouping error: 7 ERROR: column "blocks.project_id" must appear in the GROUP BY clause or be used in an aggregate function
Activity icon

Started a new Conversation Getting My Query To Get The Total Amount

I have a couple of projects and each project has a block and an activity. What I'm trying to do is list all the blocks out but also get the total price of those blocks and the total planned value of those blocks and the way I've done this is that the planned values and the pricing is in 2 different tables

The problem is, is that I'm getting the totals for individual projects, but I'm trying to add them up regardless of the project_id, that piece in the query is just to make sure that I'm getting the correct blocks for that project

Here is what my tables look like

projects table

id | name
1  | project 1
2  | project 2
3  | project 3
4  | project 4
5  | project 5

blocks table

id | project_id | block_code | price
1  | 1          | PR1  | 123
2  | 1          | PR4  | 123

activities table

id | project_id | block_code | planned
1  | 1          | PR1         | 2
2  | 1          | PR4         | 3
3  | 1          | PR7        | 1
4  | 1          | PR4        | 3

Here is my query

public function getBlocks(User $user)
{
  // one to many
  $projects = $user->projects;

  $arr = [];

  foreach($projects as $project)
  {
      $arr[] = $project->id;
  }
          
  $query = DB::connection('testing')
                      ->table('blocks')
                      ->leftJoin('activities', function($join){
                          $join->on('blocks.project_id', '=', 'activities.project_id');
                          $join->on('blocks.block_code', '=', 'activities.block_code');
                      })
                      ->leftJoin('projects', 'blocks.project_id', '=', 'projects.id')
                      ->select(
                          'blocks.project_id',
                          'blocks.block_code',
                          DB::raw('sum(activities.planned) AS total_planned'),
                          DB::raw('blocks.price * sum(activities.planned) AS total_price'),
                      )
                      ->whereIn('blocks.project_id', $arr)
                      ->groupBy(
                          'blocks.project_id',
                          'blocks.block_code',
                          'blocks.price',
                      )
                      ->get();
}
Dec
21
4 weeks ago
Activity icon

Started a new Conversation How To Split Products Based On What The Category Tab Has In Vue

I'm trying to create a page that has tabs and each tab is a category of a product. What I'm trying to do is split the products based the category, but I'm struggling on how to go about it. What I get is a list of all the products instead of only the products that is attached to that category

Here is my controller

    public function getProductCategories(User $user)
    {
        $products = Product::find($user->user_id);
        $productCategories = $products->categories();
        $categories = $productCategories->distinct()->pluck('category');

        $allCategories = Category::where('product_id', $categories->id)->groupBy('id', 'category')->get();

        return [
            'categories' => $categories,
            'allCategories' => $allCategories
        ];
    }

My vue

    <template>
        <div>
        <div class="row">
            <div class="col-md-12">
            <ul class="nav nav-tabs" id="myTab" role="tablist">
                <li class="nav-item" role="presentation" v-for="category in categories">
                <a class="nav-link active"
                    id="home-tab"
                    data-toggle="tab"
                    :href="'#'+category"
                    role="tab"
                    aria-controls="home"
                    aria-selected="true"
                >
                    {{ category }}
                </a>
                </li>
            </ul>

            <div class="tab-content" id="myTabContent">
                <div class="tab-pane fade show active" v-for="category in allCategories" :id="category.name">
                    {{ category.name }}
                </div>
            </div>
            </div>
        </div>
        </div>
    </template>

    <script>
        export default {
            props: ['user'],
            data() {
                return {
                categories: null,
                allCategories: null
                }
            },
            methods: {
            getProductCategories(){
                axios.get('/api/admin/products/'+this.user.id+'/categories').then(response => {
                this.categories = response.data.categories;
                this.allCategories = response.data.allCategories;
                })
            }
            },
            mounted(){
                this.getProductCategories();
            }
        }
    </script>
Activity icon

Replied to How To Get Only 1 Category Each

Here is my migration

$table->bigIncrements('id');
$table->string('name');
$table->string('category');
$table->text('description');

Does that help

Activity icon

Started a new Conversation How To Get Only 1 Category Each

I'm trying to pluck all the categories from a product but I want to get only one of each category. So for example I have these

T-shirts
T-shirts
T-shirts
Shoes
Pants
Pants

And what I want to grab is just

T-shirts
Shoes
Pants

Here is my code

public function getProductCategories(Product $product)
{
    $categories = $product->pluck('category')->unique('category');
    dd($categories);
}

and all that gives me is only one item.
Activity icon

Replied to Getting My Error To Display

but I'm using vue

Activity icon

Started a new Conversation Getting My Error To Display

I'm trying to get my error message to show, but it isn't showing up and I'm not getting anything in my console, but in my network tab the error is showing up.

Here is my code

<template>
    <div>
        <div class="row justify-content-center my-5">
            <div class="col-md-6">
                <div class="form">
                    <div class="card">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-5">
                                    <div class="form-group">
                                        <label>Name</label>
                                        <input type="text" class="form-control" v-model="product.name">
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="description">Description</label>
                                <textarea class="form-control" id="description" name="description" v-model="product.description">{{ product.description }}</textarea>
                            </div>
                        </div>

                        <div class="card-footer">
                            <button type="submit" class="btn btn-success" @click="updateProduct()">Update Product</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    props: ['product'],
    data() {
        return {

        }
    },
    methods: {
        updateProduct(){
            axios.put('/api/admin/products/'+this.product.id, {
                'name': this.product.name,
                'description': this.product.description
            }).then(response => {
                Swal.fire(
                    'Changes Saved',
                    'The product details have been updated',
                    'success'
                )
            }).catch(error => {
                console.log(error);
                Swal.fire(
                    'Oops!',
                    err.message,
                    'error'
                )
            })
        }
    },
    mounted(){
        
    }
}
</script>

My function

public function updateProduct(Product $product)
{
    $outstanding = Product::where('status', 'pending')
        ->first();

    if(!empty($outstanding->status) && $outstanding->status != 'Approved')
    {
        return [
            'error' => "This product is not approved"
        ];
    }
}
Activity icon

Replied to How To Get Vue To Open Up A A Tab Based On What Is In The Url

So I've managed to get it working 50%. I'm able to get the tab and the content active, but I'm not able to remove the active classes for both for the first tab.

Here is the updated code

 <template>
        <div class="card">
            <div class="card-header p-0 pt-1">
                <ul class="nav nav-tabs" id="custom-tabs-two-tab" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" 
                            :class="{active: isActive}"
                            id="client_product" 
                            data-toggle="pill" 
                            href="#client_product" 
                            role="tab"
                        >
                            Pending Client Product
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" 
                            :class="{active: isActive}"
                            id="owner_product" 
                            data-toggle="pill" 
                            href="#owner_product" 
                            role="tab"
                        >
                            Pending Owner Product
                        </a>
                    </li>
                </ul>
            </div>
            <div class="card-body table-responsive p-0">
                <div class="tab-content" id="tabContent">
                    <div class="tab-pane fade show active" :class="{show: isShow, active: isActive}" id="client_product" role="tabpanel">
                        <index-table :items="filteredClientProduct" :user="user"></index-table>
                    </div>
                    <div class="tab-pane fade" :class="{show: isShow, active: isActive}" id="owner_product" role="tabpanel">
                        <index-table :items="filteredOwnerProduct" :user="user"></index-table>
                    </div>
                </div>
            </div>
        </div>
    </template>

    <script>
        export default {
            props: ['products'],
            data() {
                return {
                    isShow: false,
                    isActive: false
                }
            },
            computed: {
                filteredClientProduct() {
                    this.bus.$on('tab-open', payload => {

                    this.products.filter(product => {
                        if(product.id === payload.id)
                        {
                            this.isShow = true;
                            this.isActive = true;
                        }
                    })
                });

                    return this.products.filter(product => product.status === "Pending Client");
                },
                filteredOwnerProduct() {
                    return this.products.filter(product => product.status === "Pending Owner");
                },
            },
            watch: {
              loaded() {
                let id = parseInt(window.location.search.substr(1));
                if (Number.isInteger(id)) {
                    this.bus.$emit('tab-open', { id: id });
                }
            }
        },
            methods: {

            },
            mounted() {

            }
        }
    </script>
Activity icon

Started a new Conversation How To Get Vue To Open Up A A Tab Based On What Is In The Url

I have a page that has a couple of tabs. What I'm trying to do is if I go to a url like this items.test/products?123 then what it needs to do is go through all the tabs and open the tab that has that ID.

I'm not sure what I need to do in order to get that to work.

I thought that maybe in the mounted section I could search for that ID and check if it is in either of the filteredClientProduct or the filteredOwnerProduct, but the filtered items didn't display, when I used console.log()

Here is my code

 <template>
        <div class="card">
            <div class="card-header p-0 pt-1">
                <ul class="nav nav-tabs" id="custom-tabs-two-tab" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" 
                            id="client_product" 
                            data-toggle="pill" 
                            href="#client_product" 
                            role="tab"
                        >
                            Pending Client Product
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" 
                            id="owner_product" 
                            data-toggle="pill" 
                            href="#owner_product" 
                            role="tab"
                        >
                            Pending Owner Product
                        </a>
                    </li>
                </ul>
            </div>
            <div class="card-body table-responsive p-0">
                <div class="tab-content" id="tabContent">
                    <div class="tab-pane fade show active" id="client_product" role="tabpanel">
                        <index-table :items="filteredClientProduct" :user="user"></index-table>
                    </div>
                    <div class="tab-pane fade" id="owner_product" role="tabpanel">
                        <index-table :items="filteredOwnerProduct" :user="user"></index-table>
                    </div>
                </div>
            </div>
        </div>
    </template>

    <script>
        export default {
            props: ['products'],
            data() {
                return {

                }
            },
            computed: {
                filteredClientProduct() {
                    return this.products.filter(product => product.status === "Pending Client");
                },
                filteredOwnerProduct() {
                    return this.products.filter(product => product.status === "Pending Owner");
                },
            },
            methods: {

            },
            mounted() {

            }
        }
    </script>
Dec
17
1 month ago
Activity icon

Replied to Email Is Getting Sent Multiple Times In Laravel

That is asking me for a user_id and there is no user_id because of moderator_id and poster_id

Activity icon

Replied to Email Is Getting Sent Multiple Times In Laravel

I tried that. I then got an error

Grouping error: 7 ERROR:  column "posts.id" must appear in the GROUP BY clause or be used in an aggregate function

so then I added id to the groupBy and I still got multiple emails for a user

Activity icon

Replied to Email Is Getting Sent Multiple Times In Laravel

sure.

<?php

namespace App;

use App\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'description', 'moderator_id', 'poster_id'];

    public function moderator()
    {
        return $this->belongsTo(User::class, 'moderator_id');
    }

    public function poster()
    {
        return $this->belongsTo(User::class, 'poster_id');
    }
}
Activity icon

Started a new Conversation Email Is Getting Sent Multiple Times In Laravel

I'm trying to send out emails to users that have outstanding posts. So the thing is, when a user posts something it first goes to the moderator and that moderator checks that the post is ok. Then once the moderator says yes it goes to the user to publish.

The problem I'm having is that my email gets sent to the same user multiple times instead of just once. What my email should contain is just a list of all outstanding posts that is waiting on that user.

Here is my code

    // Get all posts with status of Waiting on Moderator, Waiting on User, Moderator Rejected
    $outstandingPosts = Post::where('status', 'Waiting on Moderator')
                                ->orWhere('status', 'Waiting on User')
                                ->orWhere('status', 'Moderator Rejected')
                                ->get();

    foreach($outstandingPosts as $post)                            
    {
        // Get user based on whether or not they a moderator or poster
        $user = User::where('id', $post->moderator_id)
                        ->orWhere('id', $post->poster_id)
                        ->first();

        // Get all the posts that is attached to either a moderator or a poster
        $op = Post::where('moderator_id', $user->id)
                    ->orWhere('poster_id', $user->id)
                    ->get();   

        // Send email to that user with their outstanding posts
        Mail::to($user->email)->queue(new OutstandingPosts($op));
    }
Dec
15
1 month ago
Activity icon

Replied to How To Find Out If My Number Has 4 Decimal Places

I've done that and I give a number that has more then 4 decimal plages get 14 for my strlen() but if I look at a number that does have 4 decimal place I still get 14.

Activity icon

Started a new Conversation How To Find Out If My Number Has 4 Decimal Places

I'm trying to find out if my number has 4 decimal places and if it's more then that it needs to throw out an error. The problem I'm having is that I'm struggling to check for the 4 decimal places

I have this

 $rem = $num - (int)$num;

and then doing strlen((string)$rem) but when I dd($rem) I get other numbers attached to it.

For example

I have 45939.1541444444 but when I dd() I get 0.15414444440103

Dec
14
1 month ago
Activity icon

Started a new Conversation Excel Validation In Laravel

I'm trying to do some Excel validation when uploading a file. This is what my Excel file looks like.

Name   | Price 1 | Price 2 | Price 3 | Total
Item 1 | 123     | 123     | 123     | 369
Item 2 | 1200    | 300     | 900     | 2400

I need to make sure that Price 1, Price 2, Price 3 = Total for each row in the Excel sheet, and if it doesn't, then the upload fails. I'm not sure how to even start checking. I'm also using Laravel and phpoffice/phpspreadsheet. This is what I've got so far.

// $path is from the excel upload
$xl = IOFactory::load($path);
$sheet = $xl->getSheetByName('ITEMS');

$col = $sheet->getHighestDataColumn();
$row = $sheet->getHighestDataRow();

$items = $sheet->rangeToArray("A1:{$col}{$row}", null, false);

foreach($items as $item)
{

}
Dec
09
1 month ago
Activity icon

Replied to How To Get A Category Of A Product

Yes that was it thank you so much

Activity icon

Started a new Conversation How To Get A Category Of A Product

I'm not sure if I can explain this properly, but I have 3 tables

users products categories

and what I'm trying to do is get the category that is attached to a product that is attached to a user. So far I'm only able to get up to the product but I'm not sure how to get the category.

Here is my code

My controller

public function getProduct(User $user)
{
    $products = $user->product;

    return [
        'products' => $products
    ]
}

and here is my User.php

public function products()
{
    return $this->hasMany(Product::class);
}

My Product.php

public function user()
{
    return $this->belongsTo(User::class);
}

public function category()
{
    return $this->belongsTo(Category::class);
}

and my Category.php

public function products()
{
    return $this->hasMany(Product::class);
}
Dec
02
1 month ago
Activity icon

Started a new Conversation Getting Active Categories

I have a one to many relationship between users and products and I have a many to many relationship between products and categories. What I'm trying to do is list out all the active categories for products that belong to a user.

Apparently you can do this with a relationship but when I try I get a blank array.

Here is my Product.php

public function activeCategories()
{
    return $this->belongsToMany(Category::class)->where('categories.enabled', true);
}

and my ProductController

foreach($user->product->activeCategories as $cat)
{
    dd($cat);
}
Dec
01
1 month ago
Activity icon

Started a new Conversation Getting Inertia To Work With Modules In Laravel

This question is kind of with this question

https://laracasts.com/discuss/channels/laravel/using-inertia-with-modules

but I'm getting a different error.

So the issue I'm currently having is that I would like to use laravel, jetstream and inertia and I'm not able to access my modules when using inertia.

All I get is a blank page with this error in my console

[Vue warn]: Error in created hook: "Error: Cannot find module './Index'"

This is what I have in my Modules/Users/Resources/assets/js/app.js

    require('../../../../../resources/js/bootstrap');

    require('moment');

    import Vue from 'vue';

    import { InertiaApp } from '@inertiajs/inertia-vue';
    import { InertiaForm } from 'laravel-jetstream';
    import PortalVue from 'portal-vue';

    Vue.mixin({ methods: { route } });
    Vue.use(InertiaApp);
    Vue.use(InertiaForm);
    Vue.use(PortalVue);

    const users = document.getElementById('users');

    new Vue({
        render: (h) =>
            h(InertiaApp, {
                props: {
                    initialPage: JSON.parse(users.dataset.page),
                    resolveComponent: (name) => require(`../Pages/${name}`).default

                },
            }),
    }).$mount(users);

This is what I have in my Modules/Users/Resources/assets/Pages/Index.vue

    <template>
        <app-layout>
            <template #header>
                <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                    Users
                </h2>
            </template>

            <div class="py-12">
                <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
                    <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">

                    </div>
                </div>
            </div>
        </app-layout>
    </template>

    <script>
        import AppLayout from "../../../../../resources/js/Layouts/AppLayout"

        export default {
            components: {
                AppLayout,
            },
            data(){
                return {

                }
            },
            methods: {

            },
            mounted() {
                console.log('user module mounted');
            }
        }
    </script>

and when I run npm run dev I get these errors in my terminal

    ERROR in /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!/home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&)
    Module not found: Error: Can't resolve '@/Jetstream/ApplicationMark' in '/home/workspace/Documents/projects/inertia-site/resources/js/Layouts'
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!/home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&) 213:0-61 220:24-42
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue
    @ ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./Resources/assets/Pages/Index.vue?vue&type=script&lang=js&
    @ ./Resources/assets/Pages/Index.vue?vue&type=script&lang=js&
    @ ./Resources/assets/Pages/Index.vue
    @ ./Resources/assets/Pages sync ^\.\/.*$
    @ ./Resources/assets/js/app.js
    @ multi ./Resources/assets/js/app.js ./Resources/assets/sass/app.scss

    ERROR in /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!/home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&)
    Module not found: Error: Can't resolve '@/Jetstream/Dropdown' in '/home/workspace/Documents/projects/inertia-site/resources/js/Layouts'
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!/home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&) 214:0-47 221:17-28
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue
    @ ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./Resources/assets/Pages/Index.vue?vue&type=script&lang=js&
    @ ./Resources/assets/Pages/Index.vue?vue&type=script&lang=js&
    @ ./Resources/assets/Pages/Index.vue
    @ ./Resources/assets/Pages sync ^\.\/.*$
    @ ./Resources/assets/js/app.js
    @ multi ./Resources/assets/js/app.js ./Resources/assets/sass/app.scss

    ERROR in /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!/home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&)
    Module not found: Error: Can't resolve '@/Jetstream/DropdownLink' in '/home/workspace/Documents/projects/inertia-site/resources/js/Layouts'
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!/home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&) 215:0-55 222:21-36
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue
    @ ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./Resources/assets/Pages/Index.vue?vue&type=script&lang=js&
    @ ./Resources/assets/Pages/Index.vue?vue&type=script&lang=js&
    @ ./Resources/assets/Pages/Index.vue
    @ ./Resources/assets/Pages sync ^\.\/.*$
    @ ./Resources/assets/js/app.js
    @ multi ./Resources/assets/js/app.js ./Resources/assets/sass/app.scss

    ERROR in /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!/home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&)
    Module not found: Error: Can't resolve '@/Jetstream/NavLink' in '/home/workspace/Documents/projects/inertia-site/resources/js/Layouts'
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!/home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&) 216:0-45 223:16-26
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue
    @ ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./Resources/assets/Pages/Index.vue?vue&type=script&lang=js&
    @ ./Resources/assets/Pages/Index.vue?vue&type=script&lang=js&
    @ ./Resources/assets/Pages/Index.vue
    @ ./Resources/assets/Pages sync ^\.\/.*$
    @ ./Resources/assets/js/app.js
    @ multi ./Resources/assets/js/app.js ./Resources/assets/sass/app.scss

    ERROR in /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!/home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&)
    Module not found: Error: Can't resolve '@/Jetstream/ResponsiveNavLink' in '/home/workspace/Documents/projects/inertia-site/resources/js/Layouts'
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!/home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&) 217:0-65 224:26-46
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue?vue&type=script&lang=js&
    @ /home/workspace/Documents/projects/inertia-site/resources/js/Layouts/AppLayout.vue
    @ ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./Resources/assets/Pages/Index.vue?vue&type=script&lang=js&
    @ ./Resources/assets/Pages/Index.vue?vue&type=script&lang=js&
    @ ./Resources/assets/Pages/Index.vue
    @ ./Resources/assets/Pages sync ^\.\/.*$
    @ ./Resources/assets/js/app.js
    @ multi ./Resources/assets/js/app.js ./Resources/assets/sass/app.scss
Nov
27
1 month ago
Activity icon

Replied to Not Able To Get Datatables To Work With Vue

Thank you soooooooooooo much. That worked. I thought I was gonna go crazy. If you don't mind explaining could you tell me about $watch() or somewhere that explains it nicely

Activity icon

Replied to Not Able To Get Datatables To Work With Vue

yep they are. I will give what you suggested a shot

Activity icon

Replied to Using Inertia With Modules

I thought about doing a loop, but I think I might be doing something wrong in my loop. Because if I have this

resolveComponent: (name) => require(`../../Modules/Users/Resources/assets/Pages/${name}`).default

then I get my Index.vue showing up

but if I loop and do this

require('./bootstrap');

require('moment');

import Vue from 'vue';

import { InertiaApp } from '@inertiajs/inertia-vue';
import { InertiaForm } from 'laravel-jetstream';
import PortalVue from 'portal-vue';

Vue.mixin({ methods: { route } });
Vue.use(InertiaApp);
Vue.use(InertiaForm);
Vue.use(PortalVue);

const app = document.getElementById('app');

const modulesJson = require("../../modules_statuses.json");
var modulesObject = Object.keys(modulesJson);

new Vue({
    render: (h) =>
        h(InertiaApp, {
            props: {
                initialPage: JSON.parse(app.dataset.page),
                resolveComponent: (name) => {
			// LOOP IS HERE
                    for(let i = 0; i < modulesObject.length; i++){
                        require('../../Modules/'+modulesObject[i]+'/Resources/assets/Pages/'+name).default
                    }
                }
            },
        }),
}).$mount(app);

then it doesn't show up

Nov
26
1 month ago
Activity icon

Started a new Conversation Not Able To Get Datatables To Work With Vue

I'm trying to use datatables from datatables.net with my vue, but it isn't working and I'm not sure how to solve it. I'm also not getting any errors.

The one guy from the forum suggested this datatables forum, but I didn't understand what he was saying.

Here is my code

This is my Products.vue

<template>
    <div>
        <div class="card mt-4" style="width: 100%;">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-9">
                        <h3 class="text-muted mb-3">Products</h3>

                        <table class="table table-sm table-striped" id="productstable">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Price</th>
                                </tr>
                            </thead>
                
                            <tbody>
                                <tr v-for="product in displayPrdoucts" :id="product.id">
                                    <td>{{product.name}}</td>
                                    <td>{{product.price}}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        props: ['products'],
        data() {
            return {

            }
        },
        computed: {
            displayProducts() {
                if (this.products.length === 0) return [];
            }
        },
        methods: {

        },
        mounted() {

        }
    }
</script>

Here is my main.blade.php

<div id="main-page">
    <main></main>
</div>  

My Main.vue

<template>
    <div>
        <div class="container-fluid" style="max-width: 1600px;">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body">
                            <router-view :products="products"></router-view>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script type="text/javascript">
    export default {
        data() {
            return {
                products: null,
            }
        },
        methods: {
            getProjects() {
                return axios.get(`/api/${this.$route.params.id}`).then(response => {
                    this.products = response.data.products;
                });
            },
        },
        mounted() {
            this.products();
        }
    }

</script>

my main.js

import Products from "./Products";

Vue.use(VueRouter);

const router = new VueRouter({
    mode: 'history',
    base: '/',
    routes: [
        { name: "products",     path: "/products",     component: Products },
    ]
});


if (document.getElementById('main') != null) {
    const app = new Vue({
        router,
        el: '#main'
    });
}

$(document).ready( function () {
    $('#productstable').DataTable();
});
Nov
25
1 month ago
Activity icon

Started a new Conversation Clearing Redis Cache

I'm using Redis for my site and I was wondering if there is a way to clear it. For example Redis::clear() or something like that.

The reason being is that while I'm testing my Redis keeps incrementing and I would like to clear it.

I've tried cache:clear, config:clear, event:clear, horizon:clear and queue:clear, but neither of them clears Redis

Nov
22
1 month ago
Activity icon

Replied to Using Inertia With Modules

The error I'm getting is

Cannot find module '/home/shiva/Documents/projects/inertia-modules/Modules/Users/Resources/assets/Pages/Index'

And here is my code

My UsersController

    public function index()
    {
        $path = base_path('Modules/Users/Resources/assets/Pages/Index');
        return Inertia::render($path);
    }

and my app.js

require('./bootstrap');

require('moment');

import Vue from 'vue';

import { InertiaApp } from '@inertiajs/inertia-vue';
import { InertiaForm } from 'laravel-jetstream';
import PortalVue from 'portal-vue';

Vue.mixin({ methods: { route } });
Vue.use(InertiaApp);
Vue.use(InertiaForm);
Vue.use(PortalVue);

const app = document.getElementById('app');

new Vue({

    render: (h) =>
        h(InertiaApp, {
            props: {
                initialPage: JSON.parse(app.dataset.page),
                resolveComponent: (name) => require(`${name}`).default,
            },
        }),
}).$mount(app);

Nov
20
1 month ago
Activity icon

Replied to Using Inertia With Modules

Nope. It can't find it

Activity icon

Replied to Using Inertia With Modules

Unfortunately not. It couldn't find Index

Activity icon

Replied to Using Inertia With Modules

That works but then what about any other new modules I create?

Activity icon

Replied to Using Inertia With Modules

@sinnbeck so the resolveComponent: (name) => require(./Pages/${name}).default, is in my root directory and it would be ok if I had added my Index.vue to the Pages in the root directory, but I want to try to use Modules instead and it's there that I'm having a problem. Because I'm not able to get it to find the Index.vue that is in my Users Module

Activity icon

Started a new Conversation Using Inertia With Modules

I would like to use nwidart/laravel-modules and inertia together. The problem I'm having is that in my Users module when I try to access the index page I get this error in my console

Uncaught (in promise) Error: Cannot find module './Index'

I know that it's because of this

resolveComponent: (name) => require(`./Pages/${name}`).default,

but I'm not sure how to get it to work so I can use modules

Oct
20
2 months ago
Activity icon

Started a new Conversation Getting My Modal To Have The Correct Product With Livewire

Is there a way to emit from the Livewire's component in my case that is Products.php to my blade component?

What I'm trying to do is create a page where when the user wants to delete a product a popup will show up and ask if you sure that you want to delete the product and if so then click the delete button.

The problem I'm having is that my modal is selecting the last record in the database, so when I delete a product it isn't deleting the product I wanted.

Here is my code.

This is my Products.php

<?php

namespace Modules\Products\Http\Livewire;

use Modules\Products\Models\Product;
use Livewire\Component;

class Products extends Component
{
    public $modal = false;

    protected $listeners = [
        'productDeleted' => 'deleteModal',
        'close' => 'close',
        'confirmDelete' => 'delete'
    ];

    public function render()
    {
        return view('products::livewire.products', [
            'products' => Product::all()
        ]);
    }

    public function deleteModal($id)
    {
    	$user = User::find($id);
        $this->modal = true;
    }

    public function close()
    {
        $this->modal = false;
    }
}

this is my products.blade.php

@foreach($products as $product)
    <button wire:click="$emit('productDeleted', {{ $product->id }})" class="bg-red-400 hover:bg-red-300 text-red-800 font-bold py-2 px-4 rounded inline-flex items-center">Delete</button>
    @if($modal)
        @include('products::livewire.deleteProductModal', ['product' => $product])
    @endif
@endforeach

and this is my deleteProductModal.blade.php

{{ $product->title}}
Oct
19
2 months ago
Activity icon

Started a new Conversation Changing The Logo For A Two Factor Auth In Jetstream

I'm trying to use jetstreams two factor authentication. What I would like is to change the logo that I get.

So I use the Twilio Auth 2-Factor Authentication app on my phone and when I scan the QR code in the profile section I get the Laravel's logo or no logo at all if I change my app name.

I've moved the twoFactorQrCodeUrl() to my User.php so that I could edit it, but I'm still struggling to get the logo I want to show up on my Twilio Auth 2-Factor Authentication app

Activity icon

Replied to Getting Value To Show Up Using Livewire

@sinnbeck - I'm sorry about that, I forgot to add my controller and my edit blade.

Oct
18
3 months ago
Activity icon

Started a new Conversation Getting Value To Show Up Using Livewire

I'm using laravel and livewire and I'm trying to create an edit page. What I'm trying to do is get the value to show up in the textbox. So for example my edit page has product info that I'm trying to edit, but my product name isn't displaying in the textbox.

Here is my code

My ProductsController

public function edit(Product $product)
{
    return view('products::edit', [
        'product' => $product
    ]);
}

My edit.blade.php

@livewire('edit-products', ['product' => $product])

My ProductEdit.php

<?php

namespace Modules\Products\Http\Livewire;

use App\Models\Product;
use Livewire\Component;

class ProductsEdit extends Component
{
    public $name;
    public $product;

    public function render()
    {
        return view('products::livewire.edit-products', [
            'name' => $this->product->name
        ]);
    }

    public function updateProduct()
    {
        dd($this->name);
    }
}

My edit-products.blade.php

<div class="mt-1 text-sm leading-5 text-gray-900 sm:mt-0 sm:col-span-2">
    <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                    id="product_name"
                    type="text"
                    name="product_name"
                    value="{{ $product->name }}"
                    wire:model="name"
                >
</div>

<button wire:click="updateProduct" class="bg-green-400 hover:bg-green-300 text-green-800 font-bold py-2 px-4 rounded inline-flex items-center">Save</button>
Oct
12
3 months ago
Activity icon

Started a new Conversation Using A Modal To Delete A User

I'm trying to create a modal that when you click delete it will delete a record, but first I need to be able to have that modal pop up.

I know that the reason is because of this line $('#delete_{{ $user->id }}').click(function(){ but I'm not sure how to add the user id without having to add the <script>...</script> to the foreach loop

Or do I need to do that?

Here is my code

    <table class="min-w-full divide-y divide-gray-200">
        <thead>
            <tr>
                <th class="px-6 py-3 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
                    Name
                </th>

                <th class="px-6 py-3 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider text-right">
                    <a href="{{ route('users.create') }}" class="bg-green-400 hover:bg-green-300 text-green-800 font-bold py-2 px-4 rounded inline-flex items-center">Add User</a>
                </th>
            </tr>
        </thead>

        <tbody class="bg-white divide-y divide-gray-200">
            @foreach($users as $user)
                <tr>
                    <td class="px-6 py-4 whitespace-no-wrap">
                        <div class="flex items-center">
                            <div class="ml-4">
                                <div class="text-sm leading-5 font-medium text-gray-900">
                                    {{ $user->name }}
                                </div>

                                <div class="text-sm leading-5 text-gray-500">
                                    {{ $user->email }}
                                </div>
                            </div>
                        </div>
                    </td>

                    <td class="px-6 py-4 whitespace-no-wrap text-right text-sm leading-5 font-medium">
                        <button id="delete_{{ $user->id }}" class="bg-red-400 hover:bg-red-300 text-red-800 font-bold py-2 px-4 rounded inline-flex items-center">
                            Delete
                        </button>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>

    <div class="modal-display-none">
        <div class="fixed z-10 inset-0 overflow-y-auto">
            <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                <div class="fixed inset-0 transition-opacity">
                    <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
                </div>

                <span class="hidden sm:inline-block sm:align-middle sm:h-screen"></span>&#8203;

                <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"
                     role="dialog"
                     aria-modal="true"
                     aria-labelledby="modal-headline">

                    <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                        <div class="sm:flex sm:items-start">
                            <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                                <svg class="h-6 w-6 text-red-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                                </svg>
                            </div>

                            <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                                <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-headline">
                                    Delete User
                                </h3>

                                <div class="mt-2">
                                    <p class="text-sm leading-5 text-gray-500">
                                        Are you sure you want to delete this user? <br>
                                        This action cannot be undone.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                        <span class="flex w-full rounded-md shadow-sm sm:ml-3 sm:w-auto">

                            <form action="{{ route('users.delete', ['user' => $user->id]) }}" method="POST">
                                @method('DELETE')
                                @csrf

                                <button type="button"
                                        class="inline-flex justify-center w-full rounded-md border border-transparent px-4 py-2 bg-red-600 text-base leading-6 font-medium text-white shadow-sm hover:bg-red-500 focus:outline-none focus:border-red-700 focus:shadow-outline-red transition ease-in-out duration-150 sm:text-sm sm:leading-5"
                                        id="confirm_delete"
                                >
                                Delete
                            </button>
                            </form>

                        </span>

                        <span class="mt-3 flex w-full rounded-md shadow-sm sm:mt-0 sm:w-auto">
                            <button type="button" id="close" class="inline-flex justify-center w-full rounded-md border border-gray-300 px-4 py-2 bg-white text-base leading-6 font-medium text-gray-700 shadow-sm hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue transition ease-in-out duration-150 sm:text-sm sm:leading-5">
                                Cancel
                            </button>
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        .modal-display-none{
            display: none;
        }

        .modal-display{
            display: block;
        }
    </style>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function(){
            $('#delete_{{ $user->id }}').click(function(){
                console.log('delete button');
                $('.modal-display-none').removeClass('modal-display-none').addClass('modal-display');
            });

            $('#confirm_delete').click(function(){
                $('.modal-display').removeClass('modal-display').addClass('modal-display-none');
            });

            $('#close').click(function(){
                $('.modal-display').removeClass('modal-display').addClass('modal-display-none');
            });
        });
    </script>
Oct
05
3 months ago
Activity icon

Awarded Best Reply on Sorting An Array To Be Ascending Order

I managed to do it. This is the code I used

$sortedItems = $this->product->getCategoryCodes();
ksort($sortedItems, SORT_NATURAL);
Activity icon

Replied to Sorting An Array To Be Ascending Order

I managed to do it. This is the code I used

$sortedItems = $this->product->getCategoryCodes();
ksort($sortedItems, SORT_NATURAL);
Activity icon

Replied to Sorting An Array To Be Ascending Order

@sinnbeck - I get this error "Call to a member function sortBy() on array"

Oct
02
3 months ago
Activity icon

Started a new Conversation Sorting An Array To Be Ascending Order

I'm trying to sort my array in ascending order. My array is kind of working, what I mean by that is I'm getting

    P1
    P10
    P11
    P12
    P2
    P3
    P4
    P40
    P41
    P42
    P5

but what I would like is this

    P1
    P2
    P3
    P4
    P5
    P10
    P11
    P12
    P40
    P41
    P42

Here is my code

    $sortedItems = $this->product->getCategoryCodes();
    sort($sortedItems);

This is what I get when I echo out my $sortedItems

array:2 [
    "P1" => Modules\...\Product{
        -name: "Product 1"
        -description: "A description"
    }
    "P2" => Modules\...\Product{
        -name: "Product 2"
        -description: "A description 2"
    }
]
Sep
23
3 months ago
Activity icon

Started a new Conversation Deleting From A Json File

I have a json file that looks like this

    {
        "product_1": {
            "category_1": "Category 1",
            "category_2": "Category 2"
        },
    }

What I'm trying to do is when I delete a category I want to remove the "key":"value" from the json file.

Here is my code

    public function deleteCategory($product, $category)
    {
        $storage = storage_path("/products.json");
        $file = file_get_contents($storage);
        $json = json_decode($file);

        unset($json->$product->$category);

        file_put_contents($storage, json_encode($json, JSON_PRETTY_PRINT));

        return (array)$json;
    }

What happens is when I delete a category it doesn't remove it from the json.

And what I found strange was if I did this dd(file_put_contents($storage, json_encode($json, JSON_PRETTY_PRINT))) then it would work but if I only had file_put_contents($storage, json_encode($json, JSON_PRETTY_PRINT)) then it doesn't work. So I'm not sure where I'm going wrong.

Sep
21
3 months ago
Activity icon

Started a new Conversation Getting Errors When Running Npm Run Dev

When I run npm run dev in my server, I get a bunch of errors and then it says that the complete log can be found in .npm.

I checkout the log, but I'm still not sure as to why I'm getting errors. One of the reasons why I'm not sure as to what is going on is because if I run npm run dev on my local machine, it works fine.

error log

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'dev' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'predev', 'dev', 'postdev' ]
5 info lifecycle @~predev: @
6 info lifecycle @~dev: @
7 verbose lifecycle @~dev: unsafe-perm in lifecycle true
8 verbose lifecycle @~dev: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:{{ path_to_file }}/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
9 verbose lifecycle @~dev: CWD: {{ path_to_file }}
10 silly lifecycle @~dev: Args: [ '-c', 'npm run development' ]
11 silly lifecycle @~dev: Returned: code: 1  signal: null
12 info lifecycle @~dev: Failed to exec dev script
13 verbose stack Error: @ dev: `npm run development`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:315:20)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:315:20)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
14 verbose pkgid @
15 verbose cwd {{ path_to_file }}
16 verbose Linux 5.3.0-1032-azure
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "dev"
18 verbose node v12.18.2
19 verbose npm  v6.14.5
20 error code ELIFECYCLE
21 error errno 1
22 error @ dev: `npm run development`
22 error Exit status 1
23 error Failed at the @ dev script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

my package.json

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "cross-env": "^7.0",
        "laravel-mix": "^5.0.1",
        "laravel-mix-merge-manifest": "^0.1.2"
    },
    "dependencies": {
        "algoliasearch": "^4.5.1",
        "express": "^4.17.1",
        "instantsearch.css": "^7.4.5",
        "vue-bootstrap-typeahead": "^0.2.6",
        "vue-instantsearch": "^3.2.0",
        "vue-router": "^3.4.3",
        "vue-server-renderer": "^2.6.12",
        "vue-simple-suggest": "^1.10.2",
        "vuetify": "^2.3.10",
        "webpack-merge": "^5.1.4"
    }
}
Activity icon

Started a new Conversation How To Get The Agolia Search To Only Display Courses That Belong To A User

I'm trying to create a search bar that uses laravel's scout and agolia. That search bar will allow the user to search for courses that they belong to, but at the moment they can see all courses and what I would like is to only display the courses that a logged in user has access to.

my Course.php model

	<?php

	namespace App;

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

	class Course extends Model
	{
		use Searchable;	

		public function searchableAs()
		{
			return "test_search";
		}

		public function toSearchableArray()
		{
			$array = [];
			$user = User::find(request()->user()->id);

			foreach($user->course as $course)
			{
				$array = [
					'id' => $course->id,
					'name' => $course->name
				];	
			}
			

			return $array
		}

		public function users()
		{
			return $this->belongsToMany(User::class);
		}
	}

My course.blade.php

	@extends('layouts.app')

	@section('content')
	    <div id="search">
	        <search></search>
	    </div>
	@endsection

	@push('js')
		<script type="text/javascript" src="{{mix('js/search.js')}}"></script>
	@endpush

My CourseSearch.vue

	<template>
	    <ais-instant-search :search-client="searchClient" index-name="test_search">
	        <ais-autocomplete>
	            <div slot-scope="{ currentRefinement, indices, refine }">
	                <input type="search" class="form-control" @input="refine($event.currentTarget.value)">
	                <ul v-if="currentRefinement" v-for="index in indices">
	                    <li v-for="hit in index.hits">
	                        <p>
	                            <ais-highlight attribute="name" :hit="hit"/>
	                        </p>
	                    </li>
	                </ul>
	            </div>
	        </ais-autocomplete>
	    </ais-instant-search>
	</template>

	<script>
	import algoliasearch from 'algoliasearch/lite';

	export default {
	    data() {
	        return {
	            searchClient: algoliasearch(
	                'my_algolia_id',
	                'my_algolia_key'
	            ),
	        }
	    },
	    methods: {

	    },
	    mounted() {
	       
	    }
	}
	</script>