Laravel custom or extended belongsToMany - laravel

I have a table 'users' and a table 'groups'.
In the application, i am working on, the administrator can assign groups to users.
So there is a many-to-many relationship between these tables.
With the following code i defined this relation:
public function groups()
{
return $this->belongsToMany('\App\Group');
}
This way i can retrieve the groups this user is assigned to:
$users = User::with('groups')->get()
But above this, settings in the application provide the posibility to set a group for all the users.
Is it possible to define a relation so that i retrieve all groups that are related to the user plus the one that is assigned to all users according to the setting? Something like this:
public function groupsInclDefaultGroup()
{
$defaultGroupId = Setting::getSetting('defaultGroupId');
return $this->belongsToMany('\App\Group')->..??..($defaultGroupId);
}
.
$users = User::with('groupsInclDefaultGroup')->get();

Related

Laravel : Get permissions list for a user through roles table with belongtomany

I have five tables to setup relationship between 3 tables are:
+ users
+ roles
+ permissions
The relationship of users and roles are many to many through pivot table is "user_role"
The relationship of roles and permissions are also many to many through pivot table is "role_permission"
Now I want to display list users but I want bring their permissions on this list. How can I do that?
Name Email Role Permission
aaa aa#gmail.com Moderator, Customer create-post, update-post, delete-post
I have recently done this scenario by doing this way
User Model
public function roles()
{
return $this->belongsToMany(Role::class,UserRole::class);
}
Role Model
public function permissions()
{
return $this->belongsToMany(Permission::class,RolePermission::class);
}
Now when you are getting all users you need to eager load your relationships
public function index()
{
$users = User::with('roles.permissions')->get();
OR
$users = User::with(['roles' => function($query){
$query->with('permissions');
}])->get();
return view('view_name',compact('users'));
}
Note: You can also use laravel collections to reformat your roles and permissions collections for not using multiple loops. But I think you get the idea

Invalid argument supplied for foreach() in laravel when use Eloquent: Relationships

I wanna get the class name of a user via the user ID. When I input the ID of a user so I will wanna get the class name. I have three tables such as users table, classes table, and class_users table. The class_users table is born from two users table and classes table.
A users table has an id, name, email, password.
A classes table has an id, class_code, class_name.
A class_users table has an id, class_id, user_id
And this problem relates to Eloquent Relationships.
Thank you for help.
My Route:
Route::get('/find_classes/{id}','StudentController#find_classes');
My Controller function:
public function find_classes($id)
{
$users = User::find($id);
foreach($users->classes as $class)
{
echo $class->name . '<br';
dd($class);
}
}
My User Model:
public function classes()
{
return $this->belongsTo('App\Classes','class_users','user_id','class_id');
}
Looks like you might have the wrong relationship set up on your User model. You have a one to many set up, but your DB is setup to handle a many to many. I suggest you change your User model relationship:
public function classes()
{
return $this->belongsToMany('App\Classes');
}
Note, you may need to name the FK on that relation, as I see you have class_id on the table, but your actual class is named 'Classes'. Check through your relationships to ensure this is explicit on the FK where it doesn't follow Laravel convention exactly.
With this relationship, your foreach loop should work. It would be a good idea for efficiency, as mare96 noted, to eager load the classes on the $users collection when you query:
$users = User::with('classes')->find($id);

making model relationship to user, user can only access its own data

i have 2 main models and some child models with relationController to main models, now i need to add user id to both main and child models so user can only access its own data since users data stay on the same table.
i create belongsToMany relationship from user.php to the models and vice versa with pivot table but nothing happen
i have no idea how to do this since i need simplified database management in case i need to do migration..
can someone share your experience on this..
I can suggest you that you just add user_id [for Backend => backend_users_id ] to models which data you want access to owner only.
now in main model you can define belongsTo relation and in user you can define hasMany relation
main model relationship [if you want to restrict the user in backend side then you need to add backend user relation and same in backend user model]
class MainModel extends Model
{
// Adding relation to user model
public $belongsTo = [
'user' => 'RainLab\User\Models\User',
'backend_users' =>'Backend\Models\User' // for Backend
];
}
adding a relation to the user model [ you need to put this code in your plugin's boot method ]
// Extending User Model
\RainLab\User\Models\User::extend(function($model) {
$model->hasMany['mainmodel'] = ['HardikSatasiya\Plugin\Models\MainModel'];
});
// for Backend users
\Backend\Models\User::extend(function($model) {
$model->hasMany['mainmodel'] = ['HardikSatasiya\Plugin\Models\MainModel'];
});
Now access data [ Front-end side ]
// Returns the signed in user
$user = \Auth::getUser();
dd($user->mainmodel); // it will return collection of related mainmodels
// it will return related data and now its filter by owner
dd($user->mainmodel[0]->otherRelatin);
// for Backend users
// Returns the signed in user
$user = \BackendAuth::getUser();
dd($user->mainmodel); // it will return collection of related mainmodels
// it will return related data and now its filter by owner
dd($user->mainmodel[0]->otherRelatin);
Example filter data in listview based on logged in admin user [ OctoberCMS do not give such functionality out of the box, you can not hide a portion of data records you can hide entire menu or all records based on rights and roles but can not hide partial records ]
public function listExtendQuery($query)
{
$user = \BackendAuth::getUser();
$query->where('backend_users_id', $user->id);
}
to add backend_users_id you can use this code
class MainModel extends Model {
public function beforeSave()
{
$user = \BackendAuth::getUser();
$this->backend_users_id = $user->id;
}
}
if any doubt please comment.

Query all where list id has user id

I'm trying to get all the properties, in a watchlist(s) where the list has a user id.
The relationship is set up as follows.
Each watchlist is related to a user id. Each Property has a watchlist id.
I need all properties, in all the watchlists belonging to that user.
The watchlist gets the user_id automatically upon creation.
Here are my models
Watchlist
public function properties(){
return $this->hasMany('App\WatchedProperties');
}
public function user(){
return $this->belongsTo('App\User');
}
WatchedProperties
public function watchlist(){
return $this->belongsTo('App\Watchlist');
}
Query
Gets all books in every list disregarding user ids and list ids
$Watchlists = WatchedBooks::all();
Currently gets all books regardless of userid.
I need all books in all of the user's lists.
A user could have multiple lists
List A
List B
So something like
All books from all lists where the list id is related to user id.
This is what the Watchlist DB looks like
WatchlistDB
This is what the WatchedBooks DB looks like
Books in watchlist
Laravel has a beautiful solution for this: you can add a ->hasManyThrough relation to the user model. You can find more information about this type of relation in the Laravel documentation about Eloquent relationships.
The user model will look like this:
class User extends Model {
[...]
public function watchedBooks()
return $this->hasManyThrough('App\WatchedBook', 'App\Watchlist');
}
[...]
}
Then you can get all the WatchedBooks, associated with the user, using
$user->watchedBooks;
or
$user->watchedBooks()->yourBuilderQueryHere()->get();
whereHas allows you to query in relationships. More information on this can be found at https://laravel.com/docs/5.6/eloquent-relationships#querying-relationship-existence
$Watchlists = WatchedBooks::whereHas('watchlist', function($query) use ($user_id){
$query->where('user_id', $user_id)
})->get();
The script above gets all WatchedBooks that are associated with a Watchlist that is owned by a user ($user_id).

Laravel Counting and retrieving many to many relationships

I have a many to many Laravel Relationship Many Users have Many Roles
I know that I can do User::find(1)->roles()->get() to get all roles with an ID of 1 for a User but this requires me to know the ID of the role as oppossed to just its names
What sort of eloquent query could I put in my user Repository to do something like
public function getAllUsersWithRole($roleType){
//Query goes here
}
Where $roleType is the name of the Role. So I need to look up the ID of the role based on hte name and then return users that have that role ID in the pivot table
does this look like what you want:
public function getAllUsersWithRole($roleType){
$role= Role::where('name', $roleType)->first();
$users= $role->users;
return $users;
}
If you have correct relation definitions in your Eloquent models you should be able to get the users by the role name this way:
$roleType = 'YourRoleName';
$users = Role::whereType($roleType)->first()->users;
Grab the users, then get the roles for all the users.
public function getAllUsersWithRole($roleType){
$users = User::where('role_type', '=', $roleType)->get();
$roles = $users->roles()->get();
return $roles;
}

Resources