我正在使用Laravel 5.4构建一个电子商务项目,我有两个表,其中包含以下列:
类别:id,name,timestamps
产品:ID,名称,价格,描述,尺寸,图片,category_id,时间戳
这两个表通过一对多关系相互关联(一个类别有很多产品)。我将上传图像并存储在我的Laravel应用程序中的public / images文件夹中,同时图像名称存储在数据库中。当我上传所有内容工作正常时,但是当我拉出特定类别的图片时,以便在名为 Front.blade.php 的视图中显示,该视图由前控制器,我得到空白字段(它不会拉图像)。请帮忙吗?
类别模型
class Category extends Model
{
protected $fillable = ['name'];
public function products(){
return $this->hasMany('App\Product');
}
}
产品型号
class Product extends Model
{
protected $fillable = ['name', 'desctiption' , 'size', 'category_id', 'image'];
public function category()
{
return $this->belongsTo(Category::class);
}
}
产品控制器
public function store(Request $request)
{
$formInput[]=$request->image;
//validation
$this->validate($request,[
'name'=>'required',
'size'=>'required',
'description' => 'required|min:12',
'price'=>'required',
'category_id' => 'required',
'image'=>'image|mimes:png,jpg,jpeg,gif|max:100'
]);
$image=$request->image;
if($image){
$imageName=$image->getClientOriginalName();
$image->move('images',$imageName);
$formInput['image']=$imageName;
}
//Instantiate a new Project called Product
$product = new Product;
//Add the products to the Object
$product->description = $request->description;
$product->name = $request->name;
$product->price = $request->price;.
$product->image = $imageName;
$product->category_id = $request->category_id;
$product->size = $request->size;
//Save all the items to the database
$product->save();
}
FrontController
public function index(){
$items = Category::find(6)->products()->where('image' , true)->get();
return view('front.index')->withItems($items);
}
Front.blade.php
@foreach($items as $item)
<img src="{{ asset('images/'.$item->image) }}">
@endforeach
答案 0 :(得分:0)
用 orwhere() 替换 where() 子句如下,只返回 where images == true
public function index(){
$items = Category::find(6)->products()->orWhere('image','<>','')->get();
return view('front.index', compact('items'));
}