Laravel get school users - php

I am making a project that will have schools that are already seeded into the database, one user has one school.
User table has school_id
I made this relationship:
User.php
public function school(){
return $this->belongsTo('App\Models\School');
}
School.php
public function user()
{
return $this->hasMany('App\Models\User', 'school_id');
}
When i do
$school = School::where('id', 1)->first();
dd($school);
I get every field from the school model but the users aren't there,how do i make that the users appear there too without having to do?
dd($school->user)

You should use the Eloquent feature called Eager Loading
So, to eager load all the users, you should do:
School::with('user')->get();
Alternatively, if you are willing to automatically load the user without having to specify with(‘user’) every time, you can set the $with property in your School model like this:
protected $with = [‘user’];

Nvm I fixed it by doing this query
$schools = School::with('user')->get();

Related

Laravel with() works only for first record (only for record with id 1)

Imagin situation where in laravel User Eloquent model I have this kind of relationship functions:
public function serviceProvider(){
return $this->belongsTo('App\Http\Models\Users\ServiceProvider');
}
public function company(){
return $this->serviceProvider->company();
}
I have this kind of relationship in serviceProvider model:
public function company()
{
return $this->morphOne('App\Http\Models\Companies\Company', 'companyable');
}
Now in controller I write something like that:
User::where('status', '=', 1)->with('company')->get();
I know it sounds crazy but it only works for record where user's id = 1, for the rest of the record it just returns company : null
I have no idea what is going on here, Maybe I am doing something wrong? what is the problem?
If I write something like that: $user->company, it works, It works for each user, I mean for
$user = User::where('id', '=', "any id")->first;
so problem is with with()
I'm a little surprised this is working at all to be fair.
Since your User a relationship for serviceProvider set up and that has a relationship for company you don't need to have a company relationship in User.
If you want to eager/lazy load nested relationships you can just use dot notation e.g.
User::with('serviceProvider.company')->where('status', 1)->get();
Lazy load docs (scroll down to Nested Eager Loading)

Laravel Eloquent relationship Many to Many

A user can have one whitelabel.
A whitelabel can have many users.
I have a pivot table with whitelabel_id, and user_id columns
I have both relationships set up using ->belongsToMany() (with the inverse).
I am using a pivot table because I don't have a whitelabel_id on the users table (and won't be putting one in) so its defined as a many-to-many, but really it's one-to-many. I just get the first() whitelabel as there'll only be one for each user.
With this in mind. How do I select * users with the currently authenticated user's whitelabel?
I have this, it works, but is this the "Laravel" way? I feel it's slightly over engineered and Laravel would have a shorthand method.
$user->when(auth()->user()->whitelabel->first(), function ($query) {
return
$query->whereIn('id', auth()->user()->whitelabel->first()->users->pluck('id'));
})
This checks if the auth user has a whitelabel, and then gets all users with the same whitelabel.
Does Laravel have a quick shorthand for this?
Models:
class Whitelabel
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
class User
{
public function whitelabels()
{
return $this->belongsToMany(Whitelabel::class);
}
}
you can retrieve records for simple
$user = User::find(Auth::id())
$user->whitelabels
if you want return all user in Auth user's whitelabel
foreach($user->whitelabels as $whitelabel){
$whitelabel->users
}

Laravel: get a model through another table

I have gotten a model called User. in this model i have a function called UserActivity where i return this:
return $this->hasMany('App\UserActivity', 'userid');
After this i have a function that gets the activity name from the Activity table, but i do not know how to do this, i have currently gotten this:
public function Activity() {
return $this->hasManyThrough('App\UserActivity', 'App\Activity', 'userid', 'activityid');
}
And in my view i want to use this like this:
$activiteiten = \App\User::find(Auth::user()->id);
dd($activiteiten->UserActivity()->Activity());
But then i get an error saying this:
Call to undefined method Illuminate\Database\Query\Builder::Activity() (View: /var/www/vhosts/cpned.nl/intranet.cpned.nl/laravel/resources/views/dashboard.blade.php)
I can do it using inner joins but i am really wondering if i can do this with Laravel models. I do not know how currently, and because i don't know what the name is for the function in laravel i can't find it either, so I am sorry if this will be a duplicate.
My tables have the following keys and foreign keys:
Users: pk: id
user_activities: pk: userid, activityid
activities: pk: id
Thank you in advance!
You can try using eager loading.
So something like:
$activiteiten = \App\User::with('UserActivity.Activity')->find(Auth::user()->id);
dd($activiteiten->UserActivity->Activity);
Edit: So then you can do something like this:
foreach($activiteiten->UserActivity as $user_activity) {
foreach($user_activity->Activity as $activity) {
print_r($activity);
}
}
Shows how you can loop through the relationships.
The Activity function should be in the User model. So then you can call it this way:
$activiteiten = \App\User::find(Auth::user()->id);
dd($activiteiten->Activity); //gives you a collection of activities
However, you need belongsToMany function rather than hasManyThrough since the relationship between users and activities is many-to-many.
This mean you cut down going through the Intermediate model. You can check the doc on belongsToMany to understand what to do better.
A side note: Why are your functions name starting with capital letter?
Also using hasMany relations should affect the function name as well, so that 'activity' becomes 'activities' (just to keep the functionality and interpretation in sync).
Update:
//User model
public function activities() {
return $this->belongsToMany('App\Activity', 'user_activity', 'userid', 'activityid');
}
This uses the 'user_activity' table, to find the relationship between users and activities, so that you may now access by User::first()->activities for example.

Eloquent Laravel , Superior and Subordinate relationship

I have a project in laravel ,
It is an online library in which there can be three types of users , superAdmin
writersAdmin and writers,
I have already created the roles and permissions successfully
but i want to have superiors and subordinates kind of relationship in the users table
for example , the writersAdmin can have multiple writers that work for him,
is it possible to do so in the users table only or do i have to create other tables.
It can be achieved only in the user table.
for example, add superior_id column, and the save superior's id.
And, add the following code to the user model.
class User extends Eloquent {
protected $table = 'users';
public $timestamps = false;
public function parent()
{
return $this->belongsTo('User', 'superior_id');
}
public function children()
{
return $this->hasMany('User', 'superior_id');
}
}
How to use
User::with('parent')->find(1);
User::with('children')->find(1);
but, if there is more than one superiors in the user, can not be achieved in this method.
In that case, I recommend you to create other table.

Laravel 5 Relations

Database Structure:
-Users Table
-user_id
-name
-...
-Follow Table
-user_id
-follow_id
so when user follow another it will be inserted in follow table
and when get user followers
$user = User::where('user_id',$id)->first();
$user['followers'] = $user->Followers;
$user['following'] = $user->Following;
return $user;
By This Relation in User Model Side
public function Followers()
{
return $this->hasMany('App\Follow','follow_id','user_id');
}
And By This Relation in Follow Model Side
public function getUserData()
{
return $this->belongsTo('App\User','user_id','user_id');
}
It Works Fine for me and it gaves me every id But the problem is
that i want to get information about every user returned from this relation
so i should call User Model for each user returned to get his information
or what ??
The way you have you many-to-many relationship set up is almost right.
Firstly, change the Followers() method to be followers() as Laravel follows the PSR-2 standard.
Secondly, this isn't essential but change the user_id column in the users table to be just id. This is a laravel convension that does not need to be followed, however, at this point I don't see any reason not to follow it. I am assuming that you have something like:
protected $primaryKey = 'user_id';
in your User model. If you change your user_id column to id you won't have to have the above declaration anymore.
(If you don't have that line in and you want to continue using user_id as the primary key you WILL have to add that line to your User model.
Thirdly, change the relationship type in followers() to be:
public function followers()
{
return $this->belongsToMany('App\User', 'follower', 'user_id', 'follow_id');
//follower is the table name, user_id is column that relates to the current model and follow_id is the column that is for the relationships
}
With all of the above done you can now get a user with all of their followers by doing:
$user = User::with('followers')->find($id);
This will allow you to get the followers by simply doing:
$user->followers
At this point you can not get rid of you Follow model as you generally wont need a model for a pivot table.
To get the following relationship just add:
public function following()
{
return $this->belongsToMany('App\User', 'follower', 'follow_id', 'user');
}
to your User model.
Again to access this you can either:
$user = User::with('following')->find($id);
or if you have already have the user model and the relationship isn't loaded you can:
$user->load('following'); //in this case following is the name of the method where you have declared the relationship.
For more information please refer to the documentation http://laravel.com/docs/5.1/eloquent-relationships#many-to-many and http://laravel.com/docs/5.1/eloquent
Hope this helps!

Categories