George
George

Reputation: 61

get value from another table based on id laravel

i have two tables ( Factories , Products )

Factories table has two columns ( id , factory_name )

and Products table has three columns ( id , factory_id , product_name )

i want to display factory_name column in Factories table in blade.php based on factory_id in Products table

the code in Factory Model :

public function products()
{
    return $this->hasMany('App\Product');
}

and the code in Product Model :

public function factories()
{
    return $this->belongsTo('App\Factory');
}

the code in ProductsController :

public function index()
{
    $data['Products'] = Product::with('factories')->orderBy('created_at', 'desc')->get();
   
    return view('all_products')->with($data);
}

and the code in view :

 @foreach ($Products as $Product)
   <tr>
   <td>{{$Product->id}}</td>
   <td>{{$Product->factory_name}}</td>
   <td>{{$Product->product_name}}</td>               
   </tr>
 @endforeach

and this not work ... so how i get factory_name

Upvotes: 1

Views: 3595

Answers (3)

Satya Prakash
Satya Prakash

Reputation: 41

As you have shown that you are trying fetching Products along with factories

Product::with('factories')->orderBy('created_at', 'desc')->get();

So the result that you will get from this query will be in the following format

{
  id: product_id,
  factories: {
     id:factory_id,
     factory_name: factory_name,
     ...
  }
}

So in order to fetch the factory name in products list you need to use:

<td>{{$Product->factories->factory_name}}</td>

instead of

<td>{{$Product->factory_name}}</td>

Hope this solve your problems

Upvotes: 0

Bulent
Bulent

Reputation: 3411

It's always a good idea to add {{dd($data)}} to blade file to see what you have.

I think the relation between products and factories is one-to-many. In this case, it would be better if you make the function name factory instead of factories.

public function factory()
{
    return $this->belongsTo('App\Factory');
}

Unless it's a correct syntax that I'm not familiar with, the problem should be $data['Products'] and with($data). Let's change them:

public function index()
{
    $data = Product::with('factory')->orderBy('created_at', 'desc')->get();   
    return view('all_products')->with('Products', $data);
}

Now, you have $Products on your blade file.

Since you get factory_name through relation, factory info is associated with a key. You need this:

<td>{{$Product->factory->factory_name}}</td>

Upvotes: 3

Marwane Ezzaze
Marwane Ezzaze

Reputation: 1057

its easily like this :

@foreach ($Products as $Product)
   <tr>
   <td>{{$Product->id}}</td>
   <td>{{$Product->factories->factory_name}}</td>
   <td>{{$Product->product_name}}</td>               
   </tr>
 @endforeach

since you already have a relationship called factories between your two models

Upvotes: 0

Related Questions