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
- id
- name
User
- id
- name
- city_id
user_profile
- id
- user_id
- address
- phone
user_documents
- id
- user_id
- document_name
- type
User
belongsTo
one city,User
has one
profileUser
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'); }]);