为什么我的 @foreach 语句在 Laravel 中不起作用?

Why is my @foreach statement not working in Laravel?

我正在创建一个 Laravel 电子商务网站,我正在使用 Voyager 作为后端。在创建站点的 'Orders' 部分时,我 运行 遇到了问题。我正在学习本教程:https://www.youtube.com/watch?v=0lo7vzO1Fto&list=PLEhEHUEU3x5oPTli631ZX9cxl6cU_sDaR&index=19

我正在为我的订单 table 覆盖航海者视图 'read.blade.php'。我还将我的 BREAD 链接到一个名为 OrdersController.php.

的控制器

这个文件如下(下面是我添加的附加代码):

<?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'));

我的覆盖 'read.blade.php' 与正常情况相同,除了一段:

<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>

这应该 return 我的数据库中保存的所有数据,但相反,我收到此错误:

评论后

这是我的 Order.php 模型:

<?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');
    }
}

我认为行 '$products = $order->iamlush' 指的是我的订单模型中的函数 'products()',实际上应该是:

$products = $order->products

但是我 运行 这个,我得到以下错误:

我认为问题可能出在我的迁移 table 以创建 order_product 枢轴 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');
    }
}

您可以在控制器顶部添加:

Use DB;

总是在我需要获取或更改数据时使用它。

错误提示 Table 未找到。 您需要通过在终端或命令行中输入 php artisan migrate.

来迁移您的表