Reputation: 233
I've two tables: 1. categories, 2. Items
Categories.php
____________
id | name
___|________
1 | shirt
2 | shoes
Items.php
__________________________
id | categories_id | name
___|_______________|______
1 | 1 | casual
2 | 1 | dress
3 | 2 | leather
4 | 2 | jogar
Now I want to get the data of both tables using Eloquent relationship.
Desired array:
[
'name' => 'shirts',
'items' => ['casual', 'dress']
],
[
'name' => 'shoes',
'items' => ['leather', 'jogar']
]
Upvotes: 0
Views: 1749
Reputation: 47
After make model Category and item you can go to Category controller and get the data from Category by
$cat = Category::all();
don not forget add
use App\Category;
and the same thing if you want Item , Best Regards
Upvotes: 0
Reputation: 125
Link to the documentation: Eloquent Relationships.
in your Items.php
public function category()
{
return $this->belongsTo('App\Categories', 'foreign_key');
}
From that on just use:
$items = new Items;
$category = $items->category;
Upvotes: 0
Reputation: 14241
First, you need to define your relationship.
By the look of your db structure, it seems that a Category
has many Items
. So in this case it can be a One-to-Many or Many-to-many relationship. I'll go for the first one in this answer.
Now, in your models, define the relationship.
Category.php
public function items()
{
return $this->hasMany(Item::class);
}
Items.php
public function category()
{
return $this->belongsTo(Category::class);
}
Now, when querying results, you can do as simple use the with()
method to eager load the relationship items
// Perform your query and load the relationship
$categories = Category::with('items')->get();
or the load()
one, to lazy eager loading the related items.
// Perform your query
$categories = Category::all();
// load the related items
$categories->load('items');
Upvotes: 3