msslgomez

msslgomez

Member Since 1 Year Ago

Experience Points
19,310
Total
Experience

690 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
7
Lessons
Completed
Best Reply Awards
5
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 4
19,310 XP
Nov
30
3 days ago
Activity icon

Replied to Use Lodash To Filter And Sort Collection

@sinnbeck I fixed it by changing find to filter in the if statement

Nov
27
6 days ago
Activity icon

Started a new Conversation Use Lodash To Filter And Sort Collection

I'm trying to filter and then sort a collection of items to display, this is the computed method

 displayData() {
    let stor = this.sort.split(" ");

    this.filtered = _.orderBy(this.searching, [stor[0]], [stor[1]]);

    if (stor[0] === 'status') {
        this.filtered = _.find(this.searching, function (item) {
            return item.status === stor[1];
        });

        this.filtered = _.orderBy(this.searching, ['created_at'], [stor[2]]);
    }

    this.total = this.filtered.length;

    return this.filtered.slice(this.pageSize * this.page - this.pageSize, this.pageSize * this.page);
},

However this doesn't work, I get this error

Error in render: "TypeError: this.filtered.slice is not a function"

I also tried adding an else and doing the other code in there but get the same error, something to note as well, the regular let stor = this.sort.split(" ") was originally going to be something like this created_at desc but for the status its now going to sometimes be status order_request desc so now it's 3 instead of two, so that's why I created an if to check which option is being selected.

Some lodash docs https://lodash.com/docs/4.17.15#find and https://lodash.com/docs/4.17.15#orderBy

What am I doing wrong?

Nov
24
1 week ago
Activity icon

Started a new Conversation Make A Submit Method Dynamic, Use Same Method For 4 Different Forms And Routes

I'm trying to create a submit method that is very dynamic where I can use the same one for four or more different forms, data and routes. I would have, for the moment 4 different forms each with a different reference or name, same with the data, it's an object with the same name.

This is the current method that is for store and update, (they're both post because I'm sending pictures and put doesn't work) but only for one form

submit() {
    this.$refs.form.validate((valid) => {
        if (valid) {
            if (!this.settings.id) {
                this.$inertia.post('/settings', this.settings);
            } else {
                this.$inertia.post('/settings/' + this.settings.id, this.settings);
        } else {
            return false;
        }
    });
},

How can I make this work in the way I want?

Nov
23
1 week ago
Activity icon

Awarded Best Reply on Get Info Sent In Session From One Controller To Another

I changed $joker like this and that did the trick

$joker = collect([
            'products' => $products,
            'user' => auth()->user()->name,
            'status' => 'order_request',
            'client_id' => auth()->user()->id,
            'charge_id' => 'no_charge_cash',
            'charge_dateTime' => date('Y-m-j H:m:s'),
            'charge_currency' => 'cash',
            'charge_amount' => $amount,
            'delivery_customer' => $delivery['customer'],
            'delivery_phone' => $delivery['phone'],
            'delivery_email' => $delivery['email'],
        ]);
Activity icon

Replied to Get Info Sent In Session From One Controller To Another

I changed $joker like this and that did the trick

$joker = collect([
            'products' => $products,
            'user' => auth()->user()->name,
            'status' => 'order_request',
            'client_id' => auth()->user()->id,
            'charge_id' => 'no_charge_cash',
            'charge_dateTime' => date('Y-m-j H:m:s'),
            'charge_currency' => 'cash',
            'charge_amount' => $amount,
            'delivery_customer' => $delivery['customer'],
            'delivery_phone' => $delivery['phone'],
            'delivery_email' => $delivery['email'],
        ]);
Activity icon

Replied to Get Info Sent In Session From One Controller To Another

@talinon I did try that but I wanted a route in case something happened, but as long as it works I don't mind the route, this is for demonstrative purposes anyways. It's also sending $joker as empty if I do it this way

Activity icon

Started a new Conversation Get Info Sent In Session From One Controller To Another

I have a controller method that ends in two different redirects depending on the user role, all users except one create an order and the other one doesn't, I'm trying to send some information in the session to another controller to then send to a view.

This is what I have

public function cashOrder($amount, $products, $delivery)
{
    if (auth()->user()->role_id !== Role::JOKER) {
        DB::beginTransaction();
        //create order

        DB::commit();

        return redirect('cart/summary/' . $order->id);
    }

    $joker = collect();

    $joker->products = $products;

    $joker->client_id = auth()->user()->id;
    $joker->charge_id = 'no_charge_cash';
    $joker->charge_dateTime = date('Y-m-j H:m:s');
    $joker->charge_currency = 'cash';
    $joker->charge_amount = $amount;

    if ($delivery) {
        $joker->delivery_customer = $delivery['customer'];
        $joker->delivery_phone = $delivery['phone'];
        $joker->delivery_email = $delivery['email'];
    }

    return redirect('cart/joker_summary')->with('info', $joker);
}

I then have this route

 Route::get('cart/joker_summary', '[email protected]');

And this method in the other controller, if I dd($joker) after setting it I do see the info but it sends the variable joker as empty to the vue component.

    public function showJokerSummaryPage(Request $request) {
        $joker = $request->session()->get('info');

        return Inertia::render('Cart/JokerSummary', [
            'joker' => $joker
        ]);
    }

What am I doing wrong? or What is the correct way to do this?

Nov
22
1 week ago
Activity icon

Replied to Special Character Not Showing Up In Blade

@michaloravec Great I followed the link and this was what worked for me, I removed the symbol from the controller and used the code instead.

<td class="right products">
    <span style="font-family: DejaVu Sans; sans-serif;">&#8353;</span>
    {{ $product->subTotal }}
</td>
Activity icon

Replied to Can't Access Data From Collection In Blade

Sorry, I thought I did already.

Activity icon

Replied to Special Character Not Showing Up In Blade

@michaloravec I'm using barryvdh/laravel-dompdf, the reason I have those ids is to assign a special style to those fields, I cropped out the majority of the code in the blade for ease and since it's working correctly, but basically it just calls to this I guess I could change it to a regular class if that would be better.

<style>
    #products {
        border: 1px solid #39B54A;
        border-collapse: collapse;
    }
</style>
Activity icon

Started a new Conversation Special Character Not Showing Up In Blade

I can't figure out what to do, I want to show for a price but It's not showing up. This is the blade file

<html lang="en">
<head>
    <link rel="stylesheet" href="{!! url('css/general.css') !!}">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>

<body>
<main>
    <div class="container">
        <table id="products" style="width: 100%;">
            <caption>PRODUCTS</caption>
            <tr>
                <th id="products">Unit Price</th>
                <th id="products">Subtotal</th>
            </tr>
            @foreach($order['products'] as $key => $product)
                <tr>
                    <td id="products">
                        {{ $product->unit }}
                    </td>
                    <td id="products">
                        {{ $product->subTotal }}
                    </td>
                </tr>
            @endforeach
        </table>
    </div>
</main>
</body>
</html>

This is what is being sent from the controller for those specific fields

$product->unit = '₡' . number_format($prod->price, 2, '.', ',');
$product->subTotal = '₡' . number_format($prod->pivot->quantity * $prod->pivot->price, 2, '.', ',');

I've tried doing it all these different ways, but nothing works. I even tried using &#8353; but it just prints that out like a string instead of a ?

{{ $product->unit }}
{!! $product->unit !!}
{!! html_entity_decode(nl2br(e($product->unit))) !!}
{!! html_entity_decode($product->unit, ENT_QUOTES, 'UTF-8') !!} 

What am I doing wrong?

Activity icon

Replied to Can't Access Data From Collection In Blade

@michaloravec This is for a pdf so I only need to modify it like this once in my whole project, I use vue everywhere else. This works great, my symbol is showing up as a ? how can I fix that?

Activity icon

Started a new Conversation Can't Access Data From Collection In Blade

I don't really use blade so I'm a little confused on what I'm doing wrong. This is the collection in the controller

$order = Order::with('products', 'user')->findOrFail($id);

$dt = date_create($order->charge_dateTime);
$order->charge_dateTime = date_format($dt, 'm/d/Y h:m A');

$order->each(function ($or) {
    $or->products->each(function (&$prod) {
        $prod->unit = '₡' . number_format($prod->price, 2, '.', ',');
        $prod->subTotal = '₡' . number_format($prod->pivot->quantity * $prod->pivot->price, 2, '.', ',');
    });
});

But then when I try to use the unit or subTotal in the blade It doesn't display anything. I've tried two different ways but neither work.

@foreach($order['products'] as $key => $product)
    <tr>
        <td id="products">
            {{ $product['unit'] }}
        </td>
        <td id="products">
            {{ $product->subTotal }}
        </td>
    </tr>
@endforeach

What am I doing wrong?

Activity icon

Started a new Conversation Save Index To Collection After Grouping And On A Each

I'm trying to take a collection of items, group them and create a new collection that has the index since I need the index for my view.

Right now it's saving them wrong like [1,2,4] or [0,0]. This is my code

$group = $prods->groupBy('product_id');

$products = collect();

$group->each(function ($tot, $key) use ($products) {
    if (count($tot) === 1) {
        $products->push(
            [
                'product_id' => $tot[0]['product_id'],
                'product' => $tot[0]['product'],
                'index' => $key,
                'quantity_client' => $tot[0]['quantity_client'],
                'quantity_seller' => $tot[0]['quantity_seller']
            ]
        );
    } else {
        $quantity_client = 0;
        $quantity_seller = 0;

        $tot->each(function ($value) use (&$quantity_client, &$quantity_seller) {
            $quantity_client += $value['quantity_client'];
            $quantity_seller += $value['quantity_seller'];
        });

        $products->push(
            [
                'product_id' => $tot[0]['product_id'],
                'product' => $tot[0]['product'],
                'index' => $key,
                'quantity_client' => $quantity_client,
                'quantity_seller' => $quantity_seller
            ]
        );
    }
});

return $products;

What am I doing wrong?

Nov
21
1 week ago
Activity icon

Awarded Best Reply on Sending Items From Controller All Array Maps Throwing Errors

Nvm I made a mistake when setting the new products, I need to remove the [0] that was only saving the first product coming in and not all of them

if (this.$page.prop.flash.info) {
    this.products = this.$page.prop.flash.info;
}
Activity icon

Replied to Sending Items From Controller All Array Maps Throwing Errors

Nvm I made a mistake when setting the new products, I need to remove the [0] that was only saving the first product coming in and not all of them

if (this.$page.prop.flash.info) {
    this.products = this.$page.prop.flash.info;
}
Activity icon

Started a new Conversation Sending Items From Controller All Array Maps Throwing Errors

I'm doing this to send back from data after a search method

return back()->with('info', $products);

I'm doing this on my search function

sendSearch() {
    this.loading = true;
    this.$inertia.post(this.baseUrl, {
        day: this.day,
        week: this.week,
        month: this.month
    })
        .then(() => {
            if (this.$page.prop.flash.info) {
                if (this.$page.prop.flash.info[0]) {
                    this.products = this.$page.prop.flash.info[0];
                }
            }

            this.loading = false;
        })
}

But after this is completed I get about 6 errors that say about the same thing

TypeError: this.products.map is not a function

TypeError: this.searching.slice is not a function

These are all the computed methods I use, the errors point to clientGain and displayData.

computed: {
        searching() {
            if (!this.search) {
                this.total = this.products.length;
                return this.products;
            }
            this.page = 1;
            return this.products.filter(data => data.name.toLowerCase().includes(this.search.toLowerCase()));
        },
        displayData() {
            this.total = this.searching.length;

            return this.searching.slice(this.pageSize * this.page - this.pageSize, this.pageSize * this.page);
        },
        sellerGain() {
            return this.products.map(function (item) {
                return (item.quantity_seller * item.product.seller_gain)
            });
        },
        clientGain() {
            return this.products.map(function (item) {
                return (item.quantity_client * item.product.client_gain)
            });
        },
        totalGain() {
            return this.products.map(function (item) {
                return (
                    (item.quantity_client * item.product.client_gain) +
                    (item.quantity_seller * item.product.seller_gain)
                )
            });
        },
    },

What is going on and how can I fix it?

Activity icon

Started a new Conversation How To Validate 3 Fields When One One Out Of Them Is Required

I'm trying to use Element-ui to validate and a form that has 3 fields, only one can be filled so I want to validate and return errors if all are empty or more than one is empty. This is the docs https://element.eleme.io/#/en-US/component/form#custom-validation-rules.

Using that as an example I came up with this, but it's not working as intended.

var validateForm = (rule, value, callback) => {
    if (this.form.day === '' && this.form.week === '' && this.form.month === '') {
        callback(new Error('error');
    } else if (
        this.form.day !== '' && this.form.week !== '' ||
        this.form.day !== '' && this.form.month !== '' ||
        this.form.week !== '' && this.form.month !== '' ||
        this.form.day !== '' && this.form.week !== '' && this.form.month !== ''
    ) {
        callback(new Error('error2'));
    } else {
        this.$refs.form.validate();
    }
    callback();
};

I also tried this approach

methods: {
    sendSearch() {
        if (this.checkSearch === '') {
            console.log('search')
        }
    }
},
computed: {
    checkSearch() {
        if (this.form.day === '' && this.form.week === '' && this.form.month === '') {
            this.alert = 'error';
        } else if (
            this.form.day !== '' && this.form.week !== '' ||
            this.form.day !== '' && this.form.month !== '' ||
            this.form.week !== '' && this.form.month !== '' ||
            this.form.day !== '' && this.form.week !== '' && this.form.month !== ''
        ) {
            this.alert = 'error2';
        } else {
            this.alert = '';
            console.log('here')
        }
    }
},

This is what happens, when I don't fill anything out and try to execute the search I do get the first error, then I fill one field out and try again and get the console.log but if I try and click to search again nothing happens. Lets say after than I fill out another field and try to search and I get the second error, but when I remove one of the fields and try again nothing happens, I don't see the console.log.

How can I fix this? For me either way would be fine using the elemenu-ui rules or using a method/computed.

Nov
20
1 week ago
Activity icon

Replied to Creating A New Collection Items Not Getting Added

@michaloravec As usual gonna have to read the docs to fully understand but works great, Thanks!

Activity icon

Replied to Creating A New Collection Items Not Getting Added

@michaloravec @automica Thanks for your suggestions, they are all great. I'm going to use automica's because I have a role_id of 4 that I need to ignore and if I use MichalOravec's answers they don't take another user role into account, my fault for not specifying that there was one in the first place.

I also love when MichalOravec refactors my code it's always very clean and tidy.

Activity icon

Replied to Creating A New Collection Items Not Getting Added

@snapey I ended up doing this instead, the first if statement is incorrect it should be saving to `quantity_seller'. Thanks for your suggestion I'll take it into account for next time!

$orders->each(function ($order) use ($prods) {
    $order->products->each(function ($product) use ($prods, $order) {
        if ($order->user->role_id === 2) {
            $p = [
                'product_id' => $product->id,
                'product_cost' => $product->cost,
                'client_price' => $product->client_price,
                'seller_price' => $product->seller_price,
                'quantity_client' => 0,
                'quantity_seller' => $product->pivot->quantity,
                'client_gain' => $product->client_gain,
                'seller_gain' => $product->seller_gain
            ];

            $prods->push($p);
        }

        if ($order->user->role_id === 1 || $order->user->role_id === 3) {
            $p = [
                'product_id' => $product->id,
                'product_cost' => $product->cost,
                'client_price' => $product->client_price,
                'seller_price' => $product->seller_price,
                'quantity_client' => $product->pivot->quantity,
                'quantity_seller' => 0,
                'client_gain' => $product->client_gain,
                'seller_gain' => $product->seller_gain
            ];

            $prods->push($p)
        }
    });
});
Activity icon

Started a new Conversation Creating A New Collection Items Not Getting Added

I'm trying to create a new collection but it's not getting saved at all, this is what I'm trying to do

$orders->each(function ($order) use ($prods) {
    $order->products->each(function ($product) use ($order) {
        if ($order->user->role_id === 2) {
            $prods[] = [
                'product_id' => $product->id,
                'client_price' => $product->client_price,
                'seller_price' => $product->seller_price,
                'quantity_client' => $product->pivot->quantity,
                'quantity_seller' => '',
                'client_gain' => $product->client_gain,
                'seller_gain' => $product->seller_gain,
            ];
        }

        if ($order->user->role_id === 1 || $order->user->role_id === 3) {
            $prods[] = [
                'product_id' => $product->id,
                'client_price' => $product->client_price,
                'seller_price' => $product->seller_price,
                'quantity_client' => $product->pivot->quantity,
                'quantity_seller' => '',
                'client_gain' => $product->client_gain,
                'seller_gain' => $product->seller_gain,
            ];
        }
    });
});

This doesn't add anything to the collection, if I do dd($prods) inside the first if statement I do see the data there but it's gone after the whole piece of code is done.

After this the goal is to check for duplicates by the product_id and add the quantity so that there is only one entry per product with the client_quantity and seller_quantity that shows the complete totals.

Activity icon

Replied to Get All Items For The Current Month And Sort/filter The Results

@michaloravec much cleaner than mine, thanks. What can I do for the other part where I want to get the products info?

This is what I have so far

$prods = collect([]);

        $orders->each(function ($order) use ($prods) {
            $order->products->each(function ($product) use ($order) {
                if ($order->user->role_id === 2) {
                    $prods[] = [
                        'product_id' => $product->id,
                        'client_price' => $product->client_price,
                        'seller_price' => $product->seller_price,
                        'quantity_client' => 0,
                        'quantity_seller' => $product->pivot->quantity,
                        'client_gain' => $product->client_gain,
                        'seller_gain' => $product->seller_gain,
                    ];
                }

                if ($order->user->role_id === 1 || $order->user->role_id === 3) {
                    $prods[] = [
                        'product_id' => $product->id,
                        'client_price' => $product->client_price,
                        'seller_price' => $product->seller_price,
                        'quantity_client' => $product->pivot->quantity,
                        'quantity_seller' => 0,
                        'client_gain' => $product->client_gain,
                        'seller_gain' => $product->seller_gain,
                    ];
                }

            });
        });

But this doesn't save anything to $prods. What am I doing wrong?

Activity icon

Started a new Conversation Get All Items For The Current Month And Sort/filter The Results

I'm trying to make a earning page for an online store so I want to display all the products sold for the current month along with their price, also this page would be able to show the product for a different month or by a specific day.

For now I want to get the current month and then get all the orders that are within the month, which I can do like this

$fd = Carbon::now()->startOfMonth()->toDateString();
$ld = Carbon::now()->endOfMonth()->toDateString();

$orders = Order::with('products')
    ->where('charge_dateTime', '>=', $fd)
    ->where('charge_dateTime', '<=', $ld)
    ->get();

This is one order with the products

{
   //order info
   "products":[
      {
         "id":1,
         "sku":123,
         "barcode":123,
         "name":"asdfasdf",
         "description":null,
         "client_price":"15000.00",
         "seller_price":"12500.00",
         "discount":null,
         "image":null,
         "type":"product",
         "created_at":"2020-10-24 19:28:35",
         "updated_at":"2020-10-24 19:28:35",
         "cost":"0.00",
         "client_gain":"0.00",
         "seller_gain":"0.00",
         "price":"15000.00",
         "pivot":{
            "order_id":4,
            "product_id":1,
            "quantity":1,
            "price":"12500.00",
            "discount":null,
            "product_name":null
         }
      },
      {
         "id":2,
         "sku":12345,
         "barcode":12345,
         "name":"adfas",
         "description":null,
         "client_price":"123.00",
         "seller_price":"123.00",
         "discount":null,
         "image":null,
         "type":"product",
         "created_at":"2020-10-24 20:23:07",
         "updated_at":"2020-10-24 20:23:07",
         "cost":"0.00",
         "client_gain":"0.00",
         "seller_gain":"0.00",
         "price":"123.00",
         "pivot":{
            "order_id":4,
            "product_id":2,
            "quantity":1,
            "price":"123.00",
            "discount":null,
            "product_name":null
         }
      },
      {
         "id":4,
         "sku":1234,
         "barcode":1234,
         "name":"flor 7",
         "description":null,
         "client_price":"10000.00",
         "seller_price":"8000.00",
         "discount":null,
         "image":null,
         "type":"product",
         "created_at":"2020-10-25 12:47:14",
         "updated_at":"2020-11-14 14:58:10",
         "cost":"0.00",
         "client_gain":"0.00",
         "seller_gain":"0.00",
         "price":"10000.00",
         "pivot":{
            "order_id":4,
            "product_id":4,
            "quantity":1,
            "price":"8000.00",
            "discount":null,
            "product_name":null
         }
      }
   ]
}

I would need to take the products and save

product_id, 
client_price, 
seller_price, 
quantity sold to client, 
quantity sold to seller, 
client_gain, 
seller gain

for each but also add on to the quantity for a product that already exists not creating a new one.

What would be the best way

Nov
13
2 weeks ago
Activity icon

Replied to Use Locale With Vue-moment

@anzu I removed moment.js from my project,

This is how I'm using it, I use inertia.js so that's how I get the locale in the AppServiceProvider

'locale' => Session::get('locale'),
'app_locale' => App::getLocale(),

App.js

const moment = require('moment')
require('moment/locale/es')

Vue.use(require('vue-moment'), {
    moment
})

Using it in Vue.js

<h4>{{ dateTime | moment('MMMM Do YYYY') }}</h4>

export default {
    data() {
        if (!this.$page.prop.locale) {
            this.locale = this.$page.prop.app_locale;
            this.$i18n.locale = this.$page.prop.app_locale;
        } else {
            this.locale = this.$page.prop.locale;
            this.$i18n.locale = this.$page.prop.locale;
        }
    }
}

I'm using i18n for the locale switching where I have a controller method that sets the locale and a middleware that checks each request and maintains the current locale for all pages. Hope that helps

Nov
09
3 weeks ago
Activity icon

Replied to Production.ERROR: SQLSTATE[23000]: Integrity Constraint Violation: 1452 Cannot Add Or Update A Child Row: A Foreign Key Constraint Fails

I don't know what the issue was but after putting a dd after each line of this part of the code and trying again, it worked

foreach ($request->question_id as $number => $item) {
                $questions = new SurveySurveyQuestion();
                $questions->survey_id = $idSurvey;
                $questions->survey_question_id = $item['id'];
                $questions->order = $number;
                $questions->save();
            }
Activity icon

Started a new Conversation Production.ERROR: SQLSTATE[23000]: Integrity Constraint Violation: 1452 Cannot Add Or Update A Child Row: A Foreign Key Constraint Fails

I'm not having this issue locally so I don't know what could be the issue. This is the code to save

public function store(SurveySaveRequest $request)
    {
        if (auth()->user()->can('create', Survey::class)) {
            DB::beginTransaction();
            $survey = new Survey();
            $survey->name = $request->name;
            $survey->description = $request->description;
            $survey->user_id = Auth::user()->id;
            $survey->anonymous = $request->anonymous;

            $survey->save();
            $idSurvey = $survey->id;
            $evaluations = new Evaluation();
            $evaluations->survey_id = $idSurvey;
            $evaluations->init_date = $request->init_date;
            $evaluations->end_date = $request->end_date;
            $evaluations->report = $request->report;
            $report_date = $request->report_date;
            if (isset($report_date)) {
                $evaluations->report_date = $report_date;
                $add = date("Y-m-d", strtotime($report_date . "+3 week"));
                $evaluations->report_end = $add;
            }

            $evaluations->save();
            $idEvaluations = $evaluations->id;
            foreach ($request->evaluators as $item) {
                $evaluator = new EvaluationEvaluator();
                $evaluator->evaluation_id = $idEvaluations;
                if ($request->type1 === 'Persona') {
                    $evaluator->user_id = $item;
                } else if ($request->type1 === 'Grupo') {
                    $evaluator->group_id = $item;
                }
                $evaluator->save();
            }

            if ($request->evaluated) {
                foreach ($request->evaluated as $item) {
                    $evaluated = new EvaluationEvaluated();
                    $evaluated->evaluation_id = $idEvaluations;
                    if ($request->type2 === 'Persona') {
                        $evaluated->user_id = $item;
                    } else if ($request->type2 === 'Grupo') {
                        $evaluated->group_id = $item;
                    }
                    $evaluated->activity = null;
                    $evaluated->save();
                }
            } else if ($request->activity) {
                $evaluated = new EvaluationEvaluated();
                $evaluated->evaluation_id = $idEvaluations;
                $evaluated->user_id = null;
                $evaluated->group_id = null;
                $evaluated->activity = $request->activity;
                $evaluated->save();
            }

            foreach ($request->question_id as $number => $item) {
                $questions = new SurveySurveyQuestion();
                $questions->survey_id = $idSurvey;
                $questions->survey_question_id = $item['id'];
                $questions->order = $number;
                $questions->save();
            }

            DB::commit();

            return redirect('surveys');
        } else {
            return redirect('surveys');
        }

Why is this error happening on the server but not locally and how can I fix it?

Oct
29
1 month ago
Activity icon

Replied to Trying Out Jetstream Vue + Inertia Having Some Doubts

@hermes872 What does that have to do with my question?

Oct
28
1 month ago
Activity icon

Started a new Conversation Trying Out Jetstream Vue + Inertia Having Some Doubts

I'm just confused by the new project structure and it just seems complicated compared to just installing Vue and Inertia.js on a regular project. I did the fresh install just the basic

composer require laravel/jetstream
php artisan jetstream:install inertia
npm install && npm run dev
php artisan migrate

Based on this I have a couple doubts

  • Why are they still using blade files, isn't the whole point of using Vue to not use blade? I never have in my projects with vue + inertia only for error pages like 404 every other page is only vue
  • Why use Actions instead of a Controller, like there are around 5 Actions that could belong to a UserController, are Actions like methods for a Controller, what's the difference?
  • How to use Shared Data from Inertia, just like normal in the AppServiceProvider, or in the JetstreamServiceProvider or even the FortifyServiceProvider?
  • What would be a realistic usage for the teams?

I also noticed that on fresh install I can't use VueDevTools to see the info I would usually see, it even says Vue.js not detected on this site.

Maybe this seems more complicated than it really is to me since I've never used Fortify, and the app/Views and really a lot of other stuff.

Any help is greatly appreciated!

Oct
25
1 month ago
Activity icon

Replied to Filter Items By A Pivot Table Sum

@rodrigo.pedra Thank you so much this is working perfectly!

Oct
24
1 month ago
Activity icon

Replied to Filter Items By A Pivot Table Sum

@rodrigo.pedra I get a new error

SQLSTATE[42000]: Syntax error or access violation: 1140 In aggregated query without GROUP BY, expression #2 of SELECT list contains nonaggregated column 'laravel.inventory.quantity'; this is incompatible with sql_mode=only_full_group_by (SQL: select * from products where exists (select * from inventory where products.id = inventory.product_id having SUM(quantity) > 0))

Activity icon

Replied to Filter Items By A Pivot Table Sum

@rodrigo.pedra I still get the same error

Column not found: 1054 Unknown column 'total' in 'having clause'

Let me explain more, how this works is every time there is a change with the inventory a new entry in the table is being created so I would need to sum all those up and check the sum is greater than 0. In my inventory table I have product_id, quantity and the timestamps.

Activity icon

Replied to Filter Items By A Pivot Table Sum

@rodrigo.pedra That's what I had originally tried but this gives an error

Column not found: 1054 Unknown column 'total' in 'where clause'

Activity icon

Started a new Conversation Filter Items By A Pivot Table Sum

This is the code

 $prod = Product::all();

$products = $prod->filter(function ($value, $key) {
    return $value->inventorySumQuantity[0]['total'] > 0;
})->values();

I have this in my model

public function inventorySumQuantity()
    {
        return $this->hasMany(Inventory::class)
            ->selectRaw('product_id, SUM(quantity) as total')
            ->groupBy('product_id');
    }

How can I change the code to a single eloquent search instead of having to do a filter?

Oct
23
1 month ago
Activity icon

Replied to How To Write This In Vue Js?

What do you mean? That is Eloquent. You have to send that data to the view and display it there, you can't do an Eloquent search in Vue.

Oct
21
1 month ago
Activity icon

Replied to Search And Pagination Troubleshooting

@rodrigo.pedra What's the logic behind separating the code so much in so many computed methods?

Activity icon

Replied to Search And Pagination Troubleshooting

@rodrigo.pedra This is the solution I came up with

searching() {
    if (!this.search) {
        this.total = this.products.length;
        return this.products;
    }
    this.page = 1;
    return this.products.filter(data => data.name.toLowerCase().includes(this.search.toLowerCase()));
},
displayData() {
    this.total = this.searching.length;

    return this.searching.slice(this.pageSize * this.page - this.pageSize, this.pageSize * this.page);
}
Activity icon

Replied to Element-ui Table Combine Pagination And Search

@deewhy I got it

The html/vue code and the method stays the same, the error is in the displayData, this is the solution

searching() {
    if (!this.search) {
        this.total = this.categories.length;
        return this.categories;
    }
    this.page = 1;
    return this.categories.filter(data => data.name.toLowerCase().includes(this.search.toLowerCase()));
},
displayData() {
    this.total = this.searching.length;

    return this.searching.slice(this.pageSize * this.page - this.pageSize, this.pageSize * this.page);
}
Activity icon

Replied to Search And Pagination Troubleshooting

@rodrigo.pedra I need to display all the products when the search is empty, and filter them when the search isn't in your code the products don't display until the search is activated.

Oct
20
1 month ago
Activity icon

Started a new Conversation Search And Pagination Troubleshooting

I have this code, I want to be able to search through all products regardless on what page the pagination is on, however now it's doing a couple weird things.

  • Only searching through items on current page, when not on first page
  • When clearing the search the v-for doesn't reset correctly, it resets to the page is was before but the pagination number reads as 1 when it's not.
<el-row>
    <el-col>
        <el-input v-model="search"/>
    </el-col>
</el-row>

<div v-if="Object.keys(displayData).length !== 0">
    <span v-for="(prod, index) in displayData" :key="index">
        <product-component :product="prod" v-on:addToCart="addToCart"/>
    </span>

    <div>
        <el-pagination
            @current-change="handleCurrentChange"
            :page-size="pageSize"
            :total="total">
        </el-pagination>
    </div>
</div>
data() {
     return {
         search: '',
     }
},
computed: {
        displayData() {
            if (this.search == null) return this.products;

            this.filtered = this.products.filter(data => !this.search || data.name.toLowerCase().includes(this.search.toLowerCase()));
            this.total = this.filtered.length;

            let stor = this.sort.split(" ");
            if (stor[0] === 'price') {
                stor[0] = this.price;
            }

            this.filtered = _.orderBy(this.filtered, [stor[0]], [stor[1]]);

            return this.filtered.slice(this.pageSize * this.page - this.pageSize, this.pageSize * this.page);
        }
    },
    methods: {
        handleCurrentChange(val) {
            this.page = val;
        },
}

Any ideas on why this is happening and how to improve this code?

Activity icon

Replied to Element-ui Table Combine Pagination And Search

@deewhy I honestly hadn't noticed... I'm trying to see what can be done to fix this mistake. The search is working but it's not doing the search on all the items, it seems to be searching on the items on the current page and not the pages before.

Oct
16
1 month ago
Activity icon

Replied to WhereHas Returns Unexpected Item

@sinnbeck What could I do instead?

Oct
14
1 month ago
Activity icon

Awarded Best Reply on Delete Not Supported On This Route, But Deletes Anyway

Changed delete route from resource to a separate post route. That worked for some reason.

Activity icon

Replied to Delete Not Supported On This Route, But Deletes Anyway

Changed delete route from resource to a separate post route. That worked for some reason.

Activity icon

Started a new Conversation Delete Not Supported On This Route, But Deletes Anyway

I keep running into dumb issues like this after uploading changes to my server. This is not an issue locally, but when I try and delete a product I get the error above but when I refresh the page it did indeed delete it. If it's deleting it anyway why the error?

This is everything I have about deleting a product Model

 protected static function boot()
    {
        parent::boot();
        static::deleting(function ($product) {
            foreach ($product->orders as $or) {
                $order = OrderProduct::where('order_id', $or->id)->where('product_id', $product->id)->first();
                $order->product_name = $product->name;
                $order->product_id = null;
                $order->save();
            }
        });
    }

Controller

public function destroy($id)
    {
        DB::beginTransaction();
        $product = Product::findOrFail($id);
        $product->categories()->detach();
        $product->videos()->detach();
        $product->users()->detach();
        $this->removeProductImage($product);

        Inventory::where('product_id', $product->id)->delete();

        $product->delete();
        DB::commit();

        return redirect('/admin/products');
    }

I use Inertia.js so this is the request

data() {
    return {
        baseUrl: '/admin/products',
    }
}

 remove($id) {
    this.$inertia.delete(this.baseUrl + '/' + $id);
 },

I'm using a resource route.

What could be causing this error?

Activity icon

Replied to WhereHas Returns Unexpected Item

@bugsysha Thanks for your suggestion, I ended up doing this instead

$prod = Product::all();

$products = $prod->filter(function ($value, $key) {
    return $value->inventorySumQuantity[0]['total'] > 0;
})->values();
Activity icon

Started a new Conversation Send Pivot Always Even When Fk Is Empty

I have past purchase orders I would like to display but when a product gets deleted I replace in the pivot for order_product the product_id with null and save the product name in the pivot to display that since the product doesn't exist. But now when calling the relationship since product_id is null it doesn't bring anything (makes sense). This is a many to many relationship setup the regular way, the only thing is the extra columns. These are the relationships

//Product Model
    public function orders()
    {
        return $this->belongsToMany(Order::class, 'order_products')->withPivot('quantity', 'price', 'discount');
    }

//Order Model
    public function products()
    {
        return $this->belongsToMany(Product::class, 'order_products')->withPivot('quantity', 'price', 'discount', 'product_name');
    }

Is there a way to force the pivot info to be sent even if the product_id is null? If not what should I do in that case?

Activity icon

Replied to Deleting Model, Use Static Boot Set Data On Pivot

@a4ashraf You were correct that was part of the problem, this is what I have so far

 protected static function boot()
    {
        parent::boot();
        static::deleting(function ($product) {
            foreach ($product->orders as $or) {
                $order = OrderProduct::where('order_id', $or->id)->where('product_id', $product->id)->first();
                $order->product_name = $product->name;
                $order->product_id = null;
                $order->save();
            }
        });
    }
class Order extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class, 'order_products')->withPivot('quantity', 'price', 'discount', 'product_name');
    }
}

This works BUT I need to show past orders that have this product, I added the product_name in hopes to display that when the product_id is null but not since the product_id is null I don't get anything for that relationship how can I always send the pivot info even if the product_id is null?

Activity icon

Replied to Sum On Relationship (Product / Inventory)

@michaloravec The filter after works except no matter how I send it, in vue it's received as an object which is messing everything up, I need it to be an array.