skip to Main Content

there are two tables products and categories, that I created by PHPMyAdmin.
In the products table, it has a column name prd_category that has the foreign key of table categories named cat_id(primary key of categories table).

i am quite new in laravel
i want return all data from product table with category name(cat_name) from another table

//here is my controller

use AppModelsproduct;

class items extends Controller
{
    public function sample(){ 
        return product::all();
    }
}

//route

Route::get('/',[items::class,'sample']);

//model for products table

class product extends Model
{
    use HasFactory;

    function category(){
        return $this->hasOne('AppModelscategory','cat_id','prd_id');
        
    }
}

//model for category

class category extends Model
{
    protected $table='categories';
    use HasFactory;

}

pls help and thanks in advance..

3

Answers


  1. you can use this code:

    $products = product::whereHas('category',function($q)use($cat_name){
        $q->where('name',$cat_name)
    })->get();
    

    or :

    $categories = Category::where('name',$cat_name)->get()->pluck('id')->toArray()
    
    $products = product::whereIn('category_id',$categories)->get();
    
    Login or Signup to reply.
  2. Are you sure that one-to-many relation is correct? If a product can belong to many categories, you need to use many-to-many relations. Furthermore, if something else belongs to categories you should use many-to-many polymorphic relations. But let’s go with one-to-many.

    First, the relation function in Product.php looks incorrect. I think products should belong to a category.

    function category(){
       return $this->belongsTo('AppModelsCategory','cust_name','name');     
    }
    

    Then you need to define reverse relation in Category.php

    function products(){
       return $this->hasMany('AppModelsProduct','cust_name','name');     
    }
    

    When you define the relations properly, all you need yo do is to fetch data in controller:

    use AppModelsCategory
    ...
    Category::with('products')->get();
    
    Login or Signup to reply.
  3. you can use relationship with forign key like pro_id
    
    function category(){
       return $this->belongsTo('AppModelsCategory','pro_id');     
    }
    
    function products(){
       return $this->hasMany('AppModelsProduct','id');     
    }
    
    $cat = Category::with('products')->all();
    

    in Blade :

    {{ $cat->products->cat_name; }}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search