delle
delle

Reputation: 253

laravel API fetch data from table base on the unique id

I want to create an API that display and fetch data from table(users) and another table(fruits) together base on the unique id (fruit_id) common in both table.

table->users
+----------+------------+----------+--------------+
|  Id      | Fruit_id   | Name     | Gender       |
+----------+------------+----------+--------------+
|  1       | B456       | Mary     | Female       |
|  2       | O174       | James    | Male         |

table->fruits
+----------+------------+----------+--------------+
|  Id      | Fruit_id   | Name     | Quantity     |
+----------+------------+----------+--------------+
|  1       | B456       | Banana    | 22          |
|  2       | O174       | Orange    | 34          |

I created an API in laravel where fetch all data in the users table from my controller

class UserApiController extends Controller
{
    public function index()
    {
        return Users::all();
    }
}

API display result

[
    {
        id: 1,
        fruit_id: B456,
        name: Mary,
        gender: Female,
    },
    {
        id: 2,
        fruit_id: O174,
        name: James,
        gender: Male,
    }
]

I want the API to display like the below based on the unique id (fruit_id) selection that is common between both tables how will I write the code in my controller to display the desired result.

Desired result

[
    {
        id: 1,
        fruit_id: B456,
        name: Mary,
        gender: Female,
        fruits: [
            id: 1,
            fruit_id: B456,
            name: Banana,
            Quantity: 22,
        ]
    },
    {
        id: 2,
        fruit_id: O174,
        name: James,
        gender: Male,
        fruits: [
            id: 2,
            fruit_id: B456,
            name: Orange,
            Quantity: 34,
        ]        
    }
]

Upvotes: 0

Views: 722

Answers (2)

Waad Mawlood
Waad Mawlood

Reputation: 898

you need to make one-to-many relationship between tables

table->users

Id - Name - Gender

table->fruits

Id - user_id - Name - Quantity

class User extends Model{
    public function fruits(){
        return $this->hasMany(Fruit::class,'user_id');
    }
}

class Fruit extends Model{
    public function user(){
        return $this->belongsTo(User::class,'user_id');
    }
}

User::with('fruits')->get();

Upvotes: 0

Łukasz Socha
Łukasz Socha

Reputation: 158

You should create a relationship inside Model\User. Then, you can use with() or load().

Example:

Users::all()->load('fruits');

https://laravel.com/docs/8.x/eloquent-relationships#one-to-many

Upvotes: 0

Related Questions