Laravel 5 Eloquent relationship: getting the data - laravel-5

Get Data in Laravel 5.
My tables:
Users:
-id
-username
-password
Group:
-userid
-groupname
My models:
Users(model):
-hasOne(Group)
Group(model):
-belongsTo(Users)
If i do this:
$userdetails = \App\Users::find(1);
I only get user info. I need to do this to get the group:
$group = $userdetails->group;
It doesn't seems elegant to have two different variable to send to the view. Is there any better way?

You should use eloquent with().
$userdetails = \App\Users::with('group')->find(1);
you could access the group attributes like $userdetails->group->groupname

Related

Laravel Query Builder vs Laravel Eloquent ORM in many to many relation

Hi i want to get same result in join query builder as we get in many to many eloquent orm..
$users = DB::table('users')->join('role_user','users.id','=','role_user.user_id')
->join('roles','roles.id','=','role_user.role_id')
->get();
if I use this then I got separate array for same user with role.. for example XYZ user has 3 role then it give me 3 array of same user.
but I want to get it like this user has 3 roles like eloquent
you can use laravel relationship in view file for that you need to define relationship in user model
public function userRoles(){
$this->hasMany(UserRole::class);
}
in controller you need to use With that eager load userRole
To get user roles in view file
$user->userRole
// this will return array of user role related to that user

Laravel 7 - Eloquent ORM get data from 2 tables when using one to one relationship

Hello fellow programmers.
I know how to get Laravel Eloquent ORM data from relationships: one-to-one, one-to-many and many-to-many.
Not a big deal here. The issue is something that I don't know if is possible or, perhaps escaped me in my study.
Example on a relation one-to-many:
table 'Users'
id
name
table 'Phones'
id
id_user
phone_number
How can I get all fields from both tables when I run
$results = \App\Models\Users::find(1)->phones;
When I run this, $results will only give me records from the Phones table!
I know how to get that information using raw sql queries or Query Builder, but is it possible to get them with Eloquent Relationships?
Thanks in advance.
I recommend accessing relationship attributes via a relationship objects. You want to add all attributes to a phone object, but that's not a very good practice in this scenario.
You might try this:
$user = User::first();
$phones = $user->phones()->with('user')->get();
// Then you are able to access user attributes from a phone object like this:
foreach ($phones as $phone) {
print($phone->user->name);
}
A more advanced, but also faster and more proper solution is to follow this article:
$user = User::first();
$user->phones->each->setRelation('user', $user);
// Then you are able to access user attributes from a phone object like this:
foreach ($user->phones as $phone) {
print($phone->user->name);
}
When you run
$results = \App\Models\Users::find(1)->phones;
you can also include the phones like this
$results = \App\Models\Users::with('phones')->find(1);
All the phones of the user will be accessible through $results->phones.
In User model add following function:
public function phones(){
return $this->hasMany(Phone::class);
}
Then you can fetch Users with phones :
$user = User::find($id);
$phones = $user->phones()->get();
or:
User::with('phones')->get();
Fellow programmers, thank you for your appreciated responses.
Testing your solutions have made me figuring out how to achieve the goal.
In resume:
$res = User::with('phones')->first();
echo $res->name'<br>';
foreach($res->phones()->get() as $phone){
echo $phone->phone_number.'<br>';
}
This did the job.
Thank you #Kevin Bui, #Mohammad Aliyari and #Douwe de Haan for you help.

Laravel hasmanythrough where statement

I want to get the projects by the Auth::user() and company_id. I created the following:
Database:
projects:
- id
- name
- company_id
project_users:
- id
- project_id
- user_id
users:
- id
- name
- email
companies:
- id
- name
So I want to get the current user projects which belongs to company_id.
I tried the following with User Modal -> return $this->hasManyThrough('App\ProjectUsers', 'App\Project'). $user->projects->where('company_id', 1) but it returns all the data (also with company_id 2,3,4 etc).
I'm looking for a solution which can filter the projects with company_id 1 out of the query.
You have to create function in model of user
public function projectusers() {
return $this->hasMany('App\Models\project_users', 'projectID')->with('companies');
}
now create function in model projects
public function companies() {
return $this->hasMany('App\Models\companies','id', 'company_id');
}
If you are trying to limit a relation based on the results of another relation, then you need to use whereHas.
Also if you want to get the projects by some condition, I find its often most helpful to start there, with the projects.
$projects = App\Project::whereHas('company', function($q) use ($company_id) {
$q->where('id', $company_id);
})->with('users')->get();
This will grab only the projects belonging to a certain company and also eager load the users.
As you are looping, then you can get the count of the users using the relation.
foreach ($projects as $project) {
echo 'Num User: '.$project->users->count();
}

Laravel complicated relationship

My laravel app structed like this:
People: Model & Controller
Pets: Model & Controller. Has many to many relationship with People.
Abiilities: Model & Controller.
People_pets: People pets. (pivot table with people_id and pet_id). Also has 4 columns of abbility1_id, abbility2_id, abbility3_id and abbility4_id.
Now.. I built an API method to return the user pets, and it looks like this:
public function pets()
{
return $this->belongsToMany(Pet::Class, 'user_pets')->withPivot(
'abbility1_id',
'abbility2_id',
'abbility3_id',
'abbility4_id'
)->orderBy('position','asc');
}
which makes $user->pets returns the user list of pets, with the pivot information of user_pets and the abbility ids.
The question
What I want to do is add a json object to this method result named "abbilities" and get the data of the abbilities there such as name and description from the Abbilities model/controller.
How I can add the abbilities information to my query out of just the ID's?
The output of the current API CALL:
Desired output: array of Abbilities inside every pet object with the detail of the attack_id's inside $user->pets->pivot->attack1_id
You could just use the query builder and orWhere to grab the data. I don't think you can access it through relationships with the way you have it set up.
I don't know how you access your pet ability ids, but I'm guessing it's like $pet->abbility1_id.
$abbilities = Abbilities::where('id', '=', $pet->abbility1_id)
->orWhere('id', '=', $pet->abbility2_id)
->orWhere('id', '=', $pet->abbility3_id)
->orWhere('id', '=', $pet->abbility4_id)
->get();

Eloquent - Two Relationships In One?

I've been getting along slowly but surely with Laravel / Eloquent, but am now stumped:
entries Table:
id
user_id
group_id
content
users Table
id
faculty_id
name
group Table:
id
name
faculty Table
id
name
So entries are related to users and groups, and users are related to faculties - I've set up the basic relationships without a problem, and this enables me to find all entries by users from a certain faculty:
Faculty Model:
public function entries()
{
return $this->hasManyThrough('Entry','User');
}
Controller:
Faculty::find(Faculty-ID-here)->entries;
However, I now need to find entries by users that are from a certain faculty AND from a certain group, and I don't know how to write this combination this in Eloquent.
Hope that makes sense! Any suggestions?
Something like:
Entries::whereHas('user', function($q) {
$q->where('faculty_id', $facultyID);
})
->where('group_id', $groupID)
->get();
Assuming you have set up your 'user' relationship.

Resources