我有一个Laravel项目,我创建了两个表格(产品和类别),并通过一对多关系将它们相互关联。一个类别有很多产品。我创建了一个名为ProductsController的CRUD控制器,并将图像存储在Laravel应用程序中名为images in public的文件夹中。在Laravel中检索特定类别的产品5.4
当我尝试检索特定类别的存储图像并在视图中显示时,问题就开始了。 请协助。
分类模型
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'];
public function category()
{
return $this->belongsTo(Category::class);
}
}
的ProductsController
public function store(Request $request)
{
$formInput=$request->except('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'
]);
//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->category_id = $request->category_id;
$product->size = $request->size;
//Save all the items to the database
$product->save();
//image upload and save in folder in our app
$image=$request->image;
if($image){
$imageName=$image->getClientOriginalName();
$image->move('images',$imageName);
$formInput['image']=$imageName;
}
Session::flash('message' , $request->name . ' has been successfully added');
Product::create($formInput);
return redirect()->route('product.create');
}
public function show($id)
{
$items = Category::find(6)->products()->where('images' , true)->get();
return view('front.index', compact('items'));
}
Front.index视图
@foreach($items as $item)
<img src="{{ url('images', $item->image) }}">
@endforeach
是否存储在本地文件夹和数据库中的图像 – RamAnji
@RamAnji它们存储在公共/图像我Laravel应用程序.. – Martin
@Patwan检查下面详细的答案 – Sletheren