How can I connect one to many relationship in laravel eloquent? - php

Image model:
public function getImage(){
return $this->belongsTo('App\Product');
}
Product model:
public function product(){
return $this->hasMany('App\Image');
}
Controller:
public function index()
{
$products = Product::all(); //Select *
return view('product.index',compact('products'));
}
View:
#foreach($products as $product)
<td>{{ $product->getImage->image_link}}</td>
#endforeach
Error:
Trying to get property 'image_link' of non-object (View:
C:\xampp\htdocs\ecommerce\resources\views\product\index.blade.php)

Their should be a relation between post and product with product id
In Product.php
public function product(){
return $this->hasMany('App\Image');
}
then you can use $product->images->image_link

Is there a product_id field in your image table? and is there hasMany in your Product model?
In your Product model should be a relation like as below.
Product.php
public function images(){
return $this->hasMany('App\Image');
}
After then, you can use images in product for loop $product->images->image_link.

Related

MorphMany relationship returning empty array in laravel 8

I'm trying to return the product data with image with Morph relationship
I can save the data, however when I'm retrieving it, the images field has empty value.
Product Model:
protected $fillable=['name', 'description'];
public function images(){
$this->belongsToMany(Category::class);
}
Image Model:
protected $fillable=['imagable_id', 'imagable_type', 'file_name'];
public function imagable(){
return $this->morphTo();
}
Product Controller: So this where I want to retrieve the product with image on it.
public function index(){
return Product::with('images')->get();
}
This controller return only the product data, but it has empty images array field.
Your product model definition for images() is pointing at the Category model and is a belongsToMany() vs. a morphMany(). You should also adjust the spelling of imageable to be correct.
Try adjusting your relationships like this
Product Model:
public function images(){
$this->morphMany(Image::class, 'imageable');
}
Image Model:
public function imageable(){
return $this->morphTo();
}

Retrieving eloquent relationship with laravel

When I try to get the name of the Category from my product, I discovered I had to use a 'C' rather than a 'c' before it retrieved results. However when I try to get the Supplier name, the lowercase s works just fine. I was wondering what is causing this difference. Also if I dd($var), is the relations field expected to be empty. I assumed it would have something related to the relationships defined in my models.
Blade.php
<td>{{$product->Category->name}}</td>
<td>{{$product->salePrice}}</td>
<td>{{$product->stock}}</td>
<td>{{$product->supplier->company_name}}</td>
Product.php
public function category()
{
return $this->belongsTo('App\Category','category');
}
public function supplier()
{
return $this->belongsTo('App\Supplier','supplier_id');
}
Category.php
public function product()
{
return $this->hasMany('App\Product');
}
Supplier.php
public function product()
{
return $this->hasMany('App\Product');
}
You're missing a _id on your Product model:
public function category()
{
return $this->belongsTo('App\Category','category_id');
}
Or leave empty
public function category()
{
return $this->belongsTo('App\Category');
}
In your Controller
public function index()
{
$products = Product::all()->with('category');
return view('your_view', compact('products'));
}
If you dd the products
In your View you will se that the relation has been loaded because of the
Eager Loading
When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model.
#foreach($products as $product)
<td>{{$product->category->name}}</td>
<td>{{$product->salePrice}}</td>
<td>{{$product->stock}}</td>
<td>{{$product->supplier->company_name}}</td>
#endforeach

Call to undefined method App\Product::whereHas() in laravel

Hi try to get my products list in subcategory page but i'm getting this error
Call to undefined method App\Product::whereHas()
here is my function
// Subategory page included posts
public function productsubcategory($slug)
{
$products = Product::whereHas('subcategory.category', function($q) use($slug){
$q->where('slug',$slug);
})->paginate(6);
return view('frontend.subcategories', compact('products'));
}
this is my route:
Route::get('/category/{slug}/subcategory/{subslug}', ['as' => 'showbysub', 'uses' => 'IndexController#productsubcategory']);
my product model:
public function categories(){
return $this->belongsTo(Category::class);
}
public function subcategories(){
return $this->belongsTo(Subcategory::class);
}
category model:
public function products(){
return $this->hasMany(Product::class);
}
public function subcategories(){
return $this->hasMany(Subcategory::class);
}
subcategory model:
public function category(){
return $this->belongsTo(Category::class, 'category_id');
}
public function products(){
return $this->hasMany(Product::class);
}
any idea?
UPDATE:
I changed my function to:
public function productsubcategory($slug)
{
$subcategories = Subcategory::where('slug','=',$slug)->with('products')->paginate(6);
return view('frontend.subcategories', compact('subcategories'));
}
and now my page is loading but will not show any item (product).
UPDATE 2
I changed my function to this:
public function productsubcategory($slug)
{
$products = Product::with('subcategories')
->orderBy('id', 'desc')
->get();
return view('frontend.subcategories', compact('products'));
}
Now I can get products but the problem is all products will show even
if they're included other categories.
How to solve that?
I don't understand what do you mean in this lines
$products = Product::whereHas('subcategory.category', function($q) use($slug){
$q->where('slug',$slug);
})->paginate(6);
Refer to https://laravel.com/docs/5.4/eloquent-relationships. If you are trying to querying relationship, you can do like this:
$products = Product::whereHas('subcategories', function($q) use($slug){
$q->where('slug',$slug);
})->paginate(6);
or
$products = Product::whereHas('categories', function($q) use($slug){
$q->where('slug',$slug);
})->paginate(6);
The relationship name must the same with relationship method in your Product model
SOLVED
public function productsubcategory($slug, $subslug)
{
$products = Product::whereHas('subcategory', function($q) use($subslug){
$q->where('slug',$subslug);
})->get();
return view('frontend.subcategories', compact('products'));
}
and product model from subcategories change to subcategory

How to get Category info in detail page in laravel

I have a page where i show products under their subcategory url's and in top of my page i want to print the subcategory title and subcategory image, how can I do that?
here is my function:
public function productsubcategory($slug, $subslug)
{
$products = Product::whereHas('subcategory', function($q) use($subslug){
$q->where('slug',$subslug);
})->paginate(12);
return view('frontend.subcategories', compact('products'));
}
and I show my products with foreach like #foreach($products as $product) ....
The best way you doing is One to Many relationship. Use ORM for that. You will get details here: https://laravel.com/docs/5.0/eloquent
In your Category.php Model
public function subcategories()
{
return $this->hasMany('App\Subcategory', 'category_id');
}
In you Subcategory.php Model
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
public function products()
{
return $this->hasMany('App\Product', 'subcategory_id');
}
And your Product.php Model
public function subcategory()
{
return $this->belongsTo('App\Subcategory', 'subcategory_id');
}
And you will get subcategory list
$subcategories = Category::find($id)->subcategories;
And You get products
foreach($subcategories as $subCat)
{
//your code
}
And here is another link for One to Many relationship. If you read details it will help you. https://laravel.com/docs/5.5/eloquent-relationships
SOLVED
I added another query in my function so totally become like this:
public function productsubcategory($slug, $subslug)
{
$products = Product::whereHas('subcategory', function($q) use($subslug){
$q->where('slug',$subslug);
})->paginate(12);
$productss = Product::whereHas('subcategory', function($q) use($subslug){
$q->where('slug',$subslug);
})->first();
return view('frontend.subcategories', compact('products', 'productss'));
}
And here is how i show my subcategory info in their pages.
{{$productss->Subcategory->title}}
Hope this help others.

Want to fetch data from three tables in laravel 5.2

I have a little query in which I need your help, Please have a look below.
I want to fetch all the data from the products table with some conditions like city, price, Type, category.
I can fetch all the data but I can't fetch the category data from the product model with all other conditions.
Below is my tables and Eloquent relations. I am using Laravel 5.2.
products ->foreign_key('subcategory_id')
subcategories ->foreign_key('category_id')
category
users: ->foreign_key('product_id')
users table columns: ->city, price, product_id
Relations:
User Model:
public function product(){
return $this->hasMany('App\Product');
}
Product Model:
public function subcategory(){
return $this->belongsTo('App\Subcategory', 'subcategory_id');
}
Subcategory Model:
public function product(){
return $this->hasMany('App\Product', 'subcategory_id');
}
public function category(){
return $this->belongsTo('App\Category');
}
Category Model:
public function subCategory(){
return $this->hasMany('App\Subcategory');
}
public function product(){
return $this->hasManyThrough('App\Product', 'App\Subcategory');
}
Here is my query(in ProductsController.php).
$city_id, $category_id, $min_price, $max_price : demo data passed
//fetching city data
$products = Product::whereHas('user', function($query) use($city_id) {
$query->where('city_id', $city_id);
});
//fetching category data (I am not sure about this part)
$products = $products->whereHas('category', function($query) use($category_id) {
$query->where('id', $category_id);
});
//fetching price data
$products = $products->where('price', '>=', $min_price)->where('price', '<=', $max_price);
//sub category filtering
$products = $products->where('subcategory_id', 1);
$products = $products->get()->toArray();
return $products;
Any help would be appreciated. Thanks in Advance.
I think you can use with() method:
Product Model:Add the following method
public function subcategory($category_id){
return $this->belongsTo('App\Subcategory', 'subcategory_id')->with(`category`)->where('category_id',$category_id);
}
Now in Controller, you can check if the product belongs to that category,
$products = $products->subcategory($category_id);
This will get you category data also.

Categories