0

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']
 ]

3 Answers 3

3

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');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, its working. Actually I'm new on laravel and also on ORM.
@Zia Hi, if this was helpful to you, please accept the answer.
0

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;

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.