我必须在产品形式下拉显示类别值,给定的代码是从我的观点来看,错误是未定义的$类别。这是我在laravel的第一个代码,我不知道如何在其他文件中进行更改。foreach中使用哪个变量?或者我必须在ProductController中创建新功能?
<form action="/upload_product" method="post">
@csrf
<label>Choose Categories</label>
<select name="category_id" id="category" class="category">
<option disable selected>--select category--</option>
@foreach($categories as $item)
<option value="{{ $item->id }}">{{ $item->name}}</option>
@endforeach
</select>
<input type="text" name="name" placeholder="name">
<input type="number" name="sale_price" placeholder="sale_price">
</form>
模型Product.php
class Product extends Model
{
use HasFactory;
protected $table = 'products';
public $timestamps = true;
public function category(){
return $this->belongsTo('AppModelsCategory');
}
}模型Category.php
class Category extends Model
{
use HasFactory;
public $fillable = [ 'name' ];
protected $dates = [ 'deleted_at' ];
public $timestamps = true;
public function products (){
return $this->hasMany('AppModelsProduct');
}
}
ProductController.php
<?php
namespace AppHttpControllers;
use AppModelsProduct;
use AppModelsCategory;
use IlluminateHttpRequest;
class ProductController extends Controller
{
public function index()
{
$products = Product::all();
return view('products/index', ['products'=>$products]);
}
public function view()
{
$products = Product::with('category')->get();
$categories = Category::with('products')->get();
return view ('product.view')-> with([
'products' => $products,
'categories' => $categories,
]);
}
你必须在
下面使用likepublic function index(){
$products = Product::all();
$categories = Category::with('products')->get();
return view('products.index', compact('products','categories'));
}
您的索引文件中没有$categories
。基于index
方法,您只发送产品:
public function index()
{
$products = Product::all();
return view('products/index', ['products'=>$products]);
}
所以也添加类别。
public function index()
{
$products = Product::get();
return view('products/index', ['products'=>$products]);
}
有三种方法
public function index(){
$products = Product::all();
$categories = Category::with('products')->get();
return view('products.index', compact('products','categories'));
}
public function index(){
$products = Product::all();
$categories = Category::with('products')->get();
return view('products.index')->with(['products'=>$products,'categories'=>$categories]));
}
public function index(){
$data['products'] = Product::all();
$data['categories'] = Category::with('products')->get();
return view('products.index',$data);
}