Search code examples
phplaravelvoyager

Why is my @foreach statement not working in Laravel?


I am creating a Laravel eCommerce site and I am using Voyager for the back end. I've ran into an issue when creating the 'Orders' section of the site. I am following this tutorial: https://www.youtube.com/watch?v=0lo7vzO1Fto&list=PLEhEHUEU3x5oPTli631ZX9cxl6cU_sDaR&index=19

I am overwriting the voyager view 'read.blade.php' for my order table. I also have my BREAD linked to a Controller called OrdersController.php.

This file is as follows (the additional code that I have added in is below):

<?php

namespace App\Http\Controllers\Voyager;

use App\Order;
use Validator;
use App\iamlush;
use Illuminate\Http\Request;
use TCG\Voyager\Facades\Voyager;
use TCG\Voyager\Events\BreadDataAdded;
use TCG\Voyager\Events\BreadDataUpdated;
use TCG\Voyager\Http\Controllers\VoyagerBaseController;

class OrdersController extends VoyagerBaseController
{
    //***************************************
    //                _____
    //               |  __ \
    //               | |__) |
    //               |  _  /
    //               | | \ \
    //               |_|  \_\
    //
    //  Read an item of our Data Type B(R)EAD
    //
    //****************************************

    public function show(Request $request, $id)
    {
        $slug = $this->getSlug($request);

        $dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();

        $isSoftDeleted = false;

        if (strlen($dataType->model_name) != 0) {
            $model = app($dataType->model_name);

            // Use withTrashed() if model uses SoftDeletes and if toggle is selected
            if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
                $model = $model->withTrashed();
            }
            if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope'.ucfirst($dataType->scope))) {
                $model = $model->{$dataType->scope}();
            }
            $dataTypeContent = call_user_func([$model, 'findOrFail'], $id);
            if ($dataTypeContent->deleted_at) {
                $isSoftDeleted = true;
            }
        } else {
            // If Model doest exist, get data from table name
            $dataTypeContent = DB::table($dataType->name)->where('id', $id)->first();
        }

        // Replace relationships' keys for labels and create READ links if a slug is provided.
        $dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType, true);

        // If a column has a relationship associated with it, we do not want to show that field
        $this->removeRelationshipField($dataType, 'read');

        // Check permission
        $this->authorize('read', $dataTypeContent);

        // Check if BREAD is Translatable
        $isModelTranslatable = is_bread_translatable($dataTypeContent);

        // Eagerload Relations
        $this->eagerLoadRelations($dataTypeContent, $dataType, 'read', $isModelTranslatable);

        $view = 'voyager::bread.read';

        if (view()->exists("voyager::$slug.read")) {
            $view = "voyager::$slug.read";
        }

        $order = Order::find($id);
        $products = $order->iamlush;

        return Voyager::view($view, compact('dataType', 'dataTypeContent', 'isModelTranslatable', 'isSoftDeleted', 'products'));
    }
}
$order = Order::find($id);      (this gets the order id)
$products = $order->iamlush;    (this gets the product info and is there retutned below)

return Voyager::view($view, compact('dataType', 'dataTypeContent', 'isModelTranslatable', 'isSoftDeleted', 'products'));

My override 'read.blade.php' is the same as the normal apart from one section:

<div class="panel-heading" style="border-bottom:0;">
    <h3 class="panel-title">Products In Order</h3>
</div>

<div class="panel-body" style="padding-top:0;">
    <ul>
        @foreach ($products as $product)
            <li style="margin-bottom: 10px">
                <div>Product Id: {{ $product->id }}</div>
                <div>Product Name: {{ $product->name }}</div>
                <div>Product Price: {{ $product->presentPrice() }}</div>
                <div>Product Quantity: {{ $product->pivot->quantity }}</div>
            </li>
        @endforeach
     </ul>
</div>

This should return all the data held in my database but instead, I get this error:

enter image description here

After comments

Here is my Order.php model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $fillable = [
        'user_id', 'billing_email', 'billing_name', 'billing_address', 'billing_city',
        'billing_province', 'billing_postalcode', 'billing_phone', 'billing_name_on_card',
        'billing_discount', 'billing_discount_code', 'billing_total', 'payment_gateway', 'error',
    ];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function products()
    {
        return $this->belongsToMany('App\iamlush')->withPivot('quantity');
    }
}

I believe that the line '$products = $order->iamlush' refers to my function 'products()' in my order model and should actually read:

$products = $order->products

But then I run this, I get the following error:

enter image description here

I think the issue could be my migration table to create the order_product pivot table:

<?php

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

class CreateOrderProductTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('order_product', function (Blueprint $table) {
            $table->id();
            $table->integer('order_id')->unsigned()->nullable();
            $table->foreign('order_id')->references('id')
                ->on('orders')->onUpdate('cascade')->onDelete('set null');

            $table->bigInteger('product_id')->unsigned()->nullable();
            $table->foreign('product_id')->references('id')
                ->on('iamlushes')->onUpdate('cascade')->onDelete('set null');

            $table->integer('quantity')->unsigned();
            $table->timestamps();
        });
    }

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

Solution

  • The error says Table not found. You need to migrate your tables by typing in your terminal or command line php artisan migrate.