MTA
MTA

Reputation: 1073

Laravel: Merge data from two tables

I have a users table which have a relation with professions, skills, designations, locations etc. The simple user information i can get with this command app\users::find(1) and its skill information like this app\user::find(1)->skill. How can i get all information like general, profession, skills about a specific user with a single command?

For Example:

localhost:8000/users/1

This link should give me json result like below:

{
  "id": 0,
  "name": "string",
  "email": "string",
  "gender": "string",
  "age": 0,
  "mobile_number": "string",
  "company_name": "string",
  "verification_status": 0,
  "image_url": "string",
  "joining_date": "2017-04-26T12:34:34.501Z",
  "message": "string",
  "profession": {
    "id": 0,
    "name": "string"
  },
  "designation": {
    "id": 0,
    "name": "string"
  },
  "location": {
    "id": 0,
    "longitude": 0,
    "latitude": 0,
    "address": "string",
    "city": "string",
    "country": "string"
  },
  "interests": [
    {
      "id": 0,
      "name": "string",
      "custom": "string"
    }
  ],
  "skills": [
    {
      "id": 0,
      "name": "string",
      "custom": "string"
    }
  ]
}

Upvotes: 0

Views: 690

Answers (1)

Jerodev
Jerodev

Reputation: 33216

You can load all relations of that model using eager loading and then serialize that object to a json string.

Like so:

app\user::where('id', 1)->with(['profession', 'designation', '...'])->first()->toJson();

Upvotes: 1

Related Questions