Home > database >  Laravel get data from two models based on foreginkey
Laravel get data from two models based on foreginkey

Time:08-09

I have following schema DB Schema Categories table's 'id' in products table's 'category' column as foregin key

I wanted to access all products and show them on page. The problem is, in products table I have id of the category but I wanted to show the name of the category on my page. If I use hasOne or hasMany in products tabel it returns just the data of category not product

also it works only on 1 product not on Product::all()

Here is my code:

class Product extends Model
{
use HasFactory;
public function categoryName(){
    return $this->hasMany(Categorie::class);
}
}

class Categorie extends Model
{
use HasFactory;

}

Controller

function viewProducts(){
    $products = Product::all()->categoryName;
 //            ->join('categories', 'products.category_id', '=', 'categories.id')
//            ->get(['categories.categoryName', 'products.id', 'products.productName', 
// 'products.productPrice', 'products.productDescription', 'products.productImage']);

//        return view('admin.products', compact('products'));
    return $products;
}

Blade

@foreach($products as $product)

                    <tr>
                        <td>{{$product->title}}</td>
                        <td>{{$product->description}}</td>
                        <td>{{$product->quantity}}</td>
                        <td>{{$product->categoryName}}</td>
                        <td>{{$product->price}}</td>
                        <td>{{$product->discount}}</td>
                        <td><img src="{{asset('products/images/'.$product->image)}}" alt=""></td>
                        <td>
                            <a href="'addProduct' . $product->id" >Edit</a>
                            <form action="'deleteProduct' . $product->id" method="post">
                                @csrf
                                @method('DELETE')
                                <button type="submit" >Delete</button>
                            </form>
                        </td>
                    </tr>

                    @endforeach

I have tried many ways but of no vail...

CodePudding user response:

To achieve your goal you need to modify the query and make the join explicit. You need pass the fields required, set the join and then retrieve data.

Now i provide you an example with some fields.

function viewProducts(){
    $products = Product::select('products.id', 'products.title', 'products.description', 'categories.categoryName')
    ->join('categories', 'categories.id', '=', 'products.category')
    ->all(); or (get())

//        return view('admin.products', compact('products'));
    return $products;
}

  • Related