Skip to content
Advertisement

what’s the With() method in laravel?

I had refer some online references for understanding what to do with With method in laravel but still not understand. Laravel with(): What this method does?

Here are some codes which I’m not understand, may I know what the a,b,c,d,e,f refer to?

JavaScript

Advertisement

Answer

Let me give you a direct example. If you’ve user table and that user table can be related to multiple tables right?? and it is also belongs to multiple tables?.

Here, I have take four tables.

city

  1. id
  2. name

User

  1. id
  2. name
  3. city_id

user_profile

  1. id
  2. user_id
  3. address
  4. phone

user_documents

  1. id
  2. user_id
  3. document_name
  4. type

User belongsTo one city,

User has one profile

User has many documents.

Now, In the User model, you can define the relationship as below.

User.php

JavaScript

Now if you want to access this all data in the controller then you can get it by using with()

Controller

JavaScript

you’ll get all data in object as


User

id

name

  • {city data}

  • {profile}

  • {documents}


In addition, You can get multiple model nested relationship as well, Like city belongs to state and if you want to get state data with city then,

JavaScript

You can also add condition in with()

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement