简体   繁体   English

从Laravel中的foreach循环中提取特定项目

[英]Puling a specific item from a foreach loop in Laravel

I have a project with 2 tables(Categories and products). 我有一个带有2个表的项目(类别和产品)。 They have One to Many relationship. 他们有一对多的关系。 Many products have one Category. 许多产品具有一个类别。 Am pulling products of a specific category(together with its price and description) and storing in one variable so that I can use in the view. 我提取特定类别的产品(及其价格和说明),并将其存储在一个变量中,以便可以在视图中使用。 In the view am having a foreach loop whereby I want to display each row from the products table of a specific category(a product with its price and description) but it fails,,please assist? 在视图中有一个foreach循环,通过该循环我想显示特定类别的产品表中的每一行(具有价格和说明的产品),但是它失败了,请协助吗?

FrontController FrontController

public function itemOne() {
    //Get all phones(Have category of 1 ) in categories table
    $mobile = Category::find(1)
        ->products()
        ->whereNotNull("image")
        ->whereNotNull("name")
        ->whereNotNull("description")
        ->whereNotNull("price")
        ->whereNotNull("category_id")->get();

    return view('front.products')->withItems($mobile);
}

Products.blade.php Products.blade.php

@foreach($items as $item)
                <img src="{{ asset('images/'.$item->image) }}">
    <br> {{  $item->name}} <br> {{ $item->price }}
@endforeach
public function itemOne() {
    //Get all phones(Have category of 1 ) in categories table
    $mobile = Category::find(1)
        ->products()
        ->whereNotNull("image")
        ->whereNotNull("name")
        ->whereNotNull("description")
        ->whereNotNull("price")
        ->whereNotNull("category_id")->get();

    return view('front.products',compact('items'));
}

use compact in return 作为回报使用紧凑型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM