I am building an e-commerce project using Laravel 5.4, I have got 2 tables which have the following columns:
categories: id, name , timestamps
Products: id , name, price, description, size , image , category_id , timestamps
The two tables are interlinked via one to many relationship(One Category has many products). I am uploading images and storing inside public/images folder in my Laravel app while the image name is stored in the database. When I upload everything is working fine, but when I pull images of a particular category so as to display in a view called Front.blade.php which is controlled by frontcontroller, I get blank fields(it doesnt pull the images). Please assist?
Category model
class Category extends Model
{
protected $fillable = ['name'];
public function products(){
return $this->hasMany('App\Product');
}
}
Product Model
class Product extends Model
{
protected $fillable = ['name', 'desctiption' , 'size', 'category_id', 'image'];
public function category()
{
return $this->belongsTo(Category::class);
}
}
Products Controller
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
true
that's not a valid image name though. Perhaps you meant to dowhereNotNull("image")
? – apokryfoswhereNotNull("image")->where("price","<",<some number>)->get()
– apokryfos