Search code examples
phpmodelmigrationlaravel-10

Laravel 10, Model with 3 table, how?


how can I solve it (Laravel 10) so that I can query all the rows and the corresponding "instrument_types" from the 3 tables via a model?

Database and Models: https://i.sstatic.net/cuY26.png

I call it like this in my controller, but it's obviously not good: $hangszerek = Hangszer::all();

I would like to receive such json data as a response:

  {
    "h_id": 1,
    "hangszer_nev": "Gitár",
    "brutto_ar": 100000,
    "kep_url": "https://image.com/image1.png",
    "cikkszam": "4792146AG",
    "leiras": "Nagyon fain gitár",
    "tipusok":[
      {
      "t_id":1,
      "tipus_nev":"Type 1"
      },
      {
      "t_id":2,
      "tipus_nev":"Type 2"
      }
    ]
  },
  {
    "h_id": 2,
    "hangszer_nev": "Dob",
    "brutto_ar": 120000,
    "kep_url": "https://image.com/image2.png",
    "cikkszam": "47924636BF",
    "leiras": "Nagyon fain dob",
    "tipusok":[
      {
      "t_id":2,
      "tipus_nev":"Type 2"
      },
      {
      "t_id":3,
      "tipus_nev":"Type 3"
      }
    ]
  }
]```



Solution

  • You need make a relationship many to many between your models read Eloquent: Relationships in laravel documentation then you should make an Eloquent: API Resources to format json as response please read how to do it in laravel documentation