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?

 $example = Test::with('a', 'b', 'c',
            'd', 'e', 'f');

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

//User belongs To City
public function city(){
    return $this->belongsTo('AppCity','city_id','id')->withDefault();
}


//User hasone profile
public function profile(){
    return $this->hasOne('AppProfile','user_id','id')->withDefault();
}

//User hasmany document
public function documents(){
    return $this->hasMany('AppUserDocument','user_id','id')->withDefault();
}

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

Controller

AppUser::with('city','profile','documents')->get();

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,

User::with('city.state','profile','documents')->get(): 
//define state relationship in city model you'll get state data with the city as well.

You can also add condition in with()

User::with(['document'=>function ($q){
    $q->where('type','pdf');
}]);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement