Почему мой оператор @foreach не работает в Laravel? - PullRequest
0 голосов
/ 12 июля 2020

Я создаю Laravel сайт электронной коммерции и использую Voyager в качестве серверной части. У меня возникла проблема при создании раздела «Заказы» на сайте. Я следую этому руководству: https://www.youtube.com/watch?v=0lo7vzO1Fto&list=PLEhEHUEU3x5oPTli631ZX9cxl6cU_sDaR&index=19

Я перезаписываю представление путешественника «read.blade. php» для своей таблицы заказов. У меня также есть ХЛЕБ, связанный с контроллером с именем 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>

Это должно вернуть все данные, хранящиеся в моей базе данных, но вместо этого я получаю эту ошибку :

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

Я считаю, что строка '$ products = $ order-> iamlu sh' относится к моей функции 'products ()' в моя модель заказа и должна быть:

$products = $order->products

Но когда я запускаю это, я получаю следующую ошибку:

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

Ответы [ 2 ]

0 голосов
/ 13 июля 2020

Ошибка говорит, что Таблица не найдена. Вам необходимо перенести свои таблицы, набрав в терминале или в командной строке php artisan migrate.

0 голосов
/ 12 июля 2020

Вы можете добавить в верхней части вашего контроллера:

Use DB;

Всегда, когда мне нужно получить или изменить данные, мне нужно их использовать.

...