我有一個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