How can I replace raw query to laravel format

Viewed 266
DB::select("SELECT products.* ,categories.* FROM products 
INNER JOIN category_products ON category_products.product_id = products.id
INNER JOIN categories ON category_products.category_id = categories.id 
WHERE categories.slug='$slug'")

This row query working fine but I can not access their relation like

$product->Categories->first()->name

@foreach($product->Images as $image)

My product Model below :

class Product extends Model
{
    public function Category(){
        return $this->hasMany(CategoryProduct::class);
    }
    public function getCategory($id){
       return Category::find($id)->name;
    }
    public function Images(){
       return $this->hasMany(Image::class);
    }

    public function Categories()
    {
        return $this->belongsToMany(Category::class, 'category_products');
    }
}

so how can convert my code to Laravel eloquent

1 Answers
Related