nickywan123
5 months ago
791
1
Laravel

Property [purchase_number] does not exist on this collection instance.

Posted 5 months ago by nickywan123

So I am kinda in a state of confused. I know this error usually means I am assessing the an collection of object without using a foreach loop but here's the thing. I have a PurchaseController that stores items and orders after a customer checks out and sends an email to them with an invoice attachment in PDF file format. So I had to pass the $purchase variable.

In my Purchase Controller:

   public function checkoutItems(Request $request)
    {
        // Get user.
        $user = User::find(Auth::user()->id);
        // Get the items in the cart of user.
        $cartItems = Cart::whereIn('id', $request->input('cartItemId'))->get();

        // Initialize an empty array of PO Numbers
        $po_numbers = array(); // ['PO#1', 'PO#2', 'PO#3'];

        $invoiceSequence = Purchase::all()->count() + 1;

        // Create a new purchase record.
        $purchase = new Purchase;
        // Assign user to the purchase record.
        $purchase->user_id = $user->id;
        // Generate a unique number used to identify the purchase.
        $purchase->purchase_number = 'BSN' . Carbon::now()->format('Y') . str_pad($invoiceSequence, 6, "0", STR_PAD_LEFT); // BJN YYYY 00000101
        // Assign a status to the purchase. Unpaid, paid.
        $purchase->purchase_status = 1;
        // Assign the current date to the purchase in the form of DD/MM/YYYY.
        $purchase->purchase_date = Carbon::now()->format('d/m/Y');
        // Calculate total price of items in cart.
        $purchase_amount = 0;
        foreach ($cartItems as $cartItem) {
            $purchase_amount = $purchase_amount + $cartItem->total_price;
        }
        $purchase->purchase_amount = $purchase_amount;

        $purchase->save();

        $price = 0;
        $poSequence = Order::all()->count() + 1;
        // Create order record.
        // Foreach item in the cart..
        foreach ($cartItems as $cartItem) {
            // Create a new PO Number for each different panel belonging to an item.
            if (!array_key_exists($cartItem->product->panel_account_id, $po_numbers)) {
                $po_numbers[$cartItem->product->panel_account_id] = 'PO' . Carbon::now()->format('Y') . Carbon::now()->format('m') . ' ' . str_pad($poSequence, 6, "0", STR_PAD_LEFT); // PO YYYY MM 000001

                $poSequence = $poSequence + 1;
            }
        }

        // Initialize an empty variable to store panel's id.
        $panelId = null;
        // Foreach PO Number..
        foreach ($po_numbers as $key => $po_number) {
            // Create a new order record.
            $order = new Order;
            // Assign PO Number to the order.
            $order->order_number = $po_number;
            // Assign purchase id to the order
            $order->purchase_id = $purchase->id;
            // Assign the panel id to the order record
            $order->panel_id = $key;
            // Assign a status for the order. Placed, Shipped, Delivered.
            $order->order_status = 'Placed';
            // Assign empty value for order amount first.
            $orderAmount = 0;
            $order->order_amount = 0;

            $order->save();

            $panelId = $key;

            // Foreach item in the cart..
            foreach ($cartItems as $cartItem) {
                // If the cart item product's panel id matches with the current panel id..
                if ($cartItem->product->panel->account_id == $panelId) {
                    // Create a new item record.
                    $item = new Item;
                    // Assign an order number to the item
                    $item->order_number = $po_number;
                    // Assign a product id to the item
                    $item->product_id = $cartItem->product->id;
                    // Get the cart product's information. Color, dimension or length..
                    // Store it in an array, easier to access later and avoid creating another column just for an attribute of a product
                    $item->product_information = $cartItem->product_information;
                    // Assign item quantity.
                    $item->quantity = $cartItem->quantity;
                    // Assign subtotal price.
                    $item->subtotal_price = $cartItem->total_price;
                    // Assign status of the item. Placed, shipped, delivered.
                    $item->status_id = 1;
                    // After checkout, cart items should be removed from cart page
                    $cartItem->status=2002;
                    $cartItem->save();

                    $item->save();

                    $orderAmount = $orderAmount + $cartItem->total_price;
                }
            }

            $order->order_amount = $orderAmount;
            $order->save();

   *********        HERE IS WHERE IT HAPPENS    *********
            //Send the email to panel after placing order (attach with PO)

            Mail::to($order->panel->company_email)->send(new CheckoutOrder($order));

            $pdf = PDF::loadView('documents.invoice', compact('purchase'))->setPaper('a4');

            // Make a copy of the PDF invoice and store in public/storage/....
            $content = $pdf->download()->getOriginalContent();
            $pdfDestination = public_path('/storage/documents/invoice/' . $purchase->purchase_number . '/');
            $pdfName = $purchase->purchase_number;
            if (!File::isDirectory($pdfDestination)) {
                File::makeDirectory($pdfDestination, 0777, true);
            }
            File::put($pdfDestination . $pdfName . '.pdf', $content);

            //Send email to customer after placing order( attach with invoice)
            $message = new InvoiceEmailCustomer($purchase);
            $message->attachData($pdf->output(), "invoice.pdf");
            Mail::to($purchase->user->email)->send($message);
        }

And I pass it to my documents.invoice via compact.

My invoice blade(parts of it):

<body>

    @php
    $url = URL::signedRoute
    ('confirm-order', [
    'purchase_num' => $purchase->purchase_number,

    ]);
    @endphp
    <div class="container">
        <span class="float-left"> <img src="{{ asset('images/Invoice-Logo.png') }}" style="width:15%;" alt="No Logo"></span>
        <img style="float:right; margin-bottom:10px;" src="data:images/png;base64, {{ base64_encode(QrCode::format('png')->size(100)->generate($url)) }} ">
    </div> <br> <br>

    <div>

        <div style="font-size:10px;float:left; width:50%;">
            <table style="border: 1px solid black; max-width:300px; ">
                <tr>
                    <td>Receiver:</td>
                    <td>{{$purchase->user->userInfo->full_name}}</td>
                </tr>

                <tr>
                    <td>Attention To:</td>
                    <td>-</td>
                </tr>

                <tr>
                    <td>Contact No:</td>

                    <td>{{ $purchase->user->userInfo->contacts->where('is_mobile', 1)->first()->contact_num }}</td>

                </tr>
            </table>

        </div>


        <div style="font-size:10px;float:right; margin-right:100px; width:50%;">


            <table style="border: 1px solid black; max-width:300px;  ">
                <tr>
                    <td>Deliver To:</td>
                    <td>{{$purchase->user->userInfo->addresses->where('is_shipping_address',1)->first()->address_1}}
                        {{$purchase->user->userInfo->addresses->where('is_shipping_address',1)->first()->address_2}}
                        {{$purchase->user->userInfo->addresses->where('is_shipping_address',1)->first()->address_3}}
                        {{$purchase->user->userInfo->addresses->where('is_shipping_address',1)->first()->postcode}}
                        {{$purchase->user->userInfo->addresses->where('is_shipping_address',1)->first()->city}}

                    </td>
                </tr>

                <tr>
                    <td>Attention To:</td>
                    <td>empty</td>
                </tr>

                <tr>
                    <td>Contact No:</td>
                    <td></td>
                </tr>
            </table>

        </div>

So all in all everything is able to pass the data successfully, when I opened my invoice PDF in email, it works fine.

Now I created another method to do the same thing except instead of an email, I just click on my orders and it should redirect me to invoice page in PDF.

Order Controller:

 /** Return invoice for the particular order in PDF format**/

   public function invoice(){
    // Get user.
    $user = User::find(Auth::user()->id);
    $purchase = $user->purchases;
    $pdf = PDF::loadView('documents.invoice',compact('purchase'))->setPaper('A4');
    return $pdf->stream('invoice.pdf');
   }

So when I clicked it brings me to the invoice page which is correct but somehow it says Property [purchase_number] does not exist on this collection instance. How is my purchase controller able to pass the data to the view successfully while my order controller could not pass?

They are both passing to the same invoice view.

Please sign in or create an account to participate in this conversation.