Laravel: how order by many to many table? - laravel

I have tables
users
id
username
role
id
name
users_role
user_id
role_id
I have users listing and I want ability to sort by username and role_id, how I can do this?
users
1:first
2:second
3:third
roles
1:admin
2:customer
users_role
1:1
1:2
2:2
3:2
Sort can be by first user role_id(or for max role_id -> if user have roles 1 and 2 sort by 2)

First of all, you need to create relationships for two model: User and Role (i suppose that we have three tables: users, roles and role_user:
class User extends Model
{
public function roles() {
return $this->belongsToMany('\App\Role');
}
}
class Role extends Model
{
public function users()
{
return $this->belongsToMany('\App\User');
}
}
Next, with this query you can have list of users and roles, sort by username ASC and role_id DESC
\App\User::with(array('roles' => function($query) {
$query->orderBy('role_id', 'DESC');
}))
->orderBy('username', 'ASC')
->get();

Related

Best Practice to Get Roles of Active Users = Auth::user()

I have 3 table
users
roles
role_users
this table created by Orchid Platform, i want to get role name of Auth::user() in Dashboard Laravel 8 (/home) from role_users table, i have tried to add role_id to users table, thats realy work.
But i want use role_users, because Orchid Platform use role_users.
Please help me, thank you.
I don't know about "Orchid Platform" but that User<->Role (ManyToMany) relationship is a pretty common database structure.
users
id - integer
name - string
roles
id - integer
name - string
role_user
user_id - integer
role_id - integer
User Model:
class User extends Model
{
/**
* The roles that belong to the user.
*/
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
Role Model:
class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany(User::class);
}
}
To get roles of the authenticated User
$user = User::find(1);
foreach ($user->roles as $role) {
//
}
If your users will only have 1 role, you can just use a method in your User model to get first role of the User.
public function getRole(){
return $this->roles()->first();
}
Now, you can used this way:
Auth::user()->getRole()->name

Get user that belongs to a specific role in laravel

I have following table for roles:
id | name | user_id
1 Admin NULL
2 Accountant 1
3 Storekeeper 1
and user table like this:
id | name | role_id
1 Admin 1
2 xyz 2
3 xyz 3
I want to retrieve all data from users table that have been created by Admin in my case that have user_id 1.
I'm using this relation:
public function Role()
{
return $this->hasMany('App\Models\Role', 'user_id', 'id');
}
$users = User::with('Role')->whereHas('Role', function($query) {
$query->where('user_id', 1);
})->get();
but this is not returning data from users table it is returning rows from roles table only that have user_id 1.
larar
From your database structure, the relation user to role is belongsTo not hasMany
each user has one role.
each role can be assigned to many users.
User ==Belongs to==> Role
Role ==Has many==> User
public function role()
{
return $this->belongsTo('App\Models\Role', 'role_id', 'id');
}
And then you call the users with admin role like this.
$adminsWithRole = User::with('role')->whereHas('Role', function($query) {
$query->where('roles.id', 1);
})->get();
Lets say you want to get the Created roles by the users that are admin
This needs its own relation
public function createdRoles()
{
return $this->hasMany('App\Models\Role', 'user_id', 'id');
}
The get the created roles by all users that have the role admin
$adminsWithCreatedRoles = User::with('createdRoles')->whereHas('Role', function($query) {
$query->where('roles.id', 1);
})->get();

Fetch data that don't exist in pivot table column - Laravel 6

I have two tables viz
1. users
columns: id, name
2. user_access
columns: id, user_id, user_access_id
user access is a pivot table that defines the relationship between users table and users table itself. For example, a user might have access to data of some other users.
I have defined this relationship in User model.
Now I want to fetch those user ids for a user which don't exist in user_access table.
For example, a user may have access to id 1 & 2 but he doesn't have access to id 3 & 4, so I want to fetch id 3 & 4 and not 1 & 2.
To achieve this I use whereDoesntHave eloquent but it's not working for relationship on the same tables and I get the following error
Facade\Ignition\Exceptions\ViewException
Call to undefined method Illuminate\Database\Eloquent\Builder::getRelated() (View: C:\xampp\htdocs\prd_tracker\resources\views\tracker\ticket\script.blade.php)
but it does work for different tables.
Here is my code
User Model
public function userAccess()
{
return $this->belongsToMany('App\User', 'user_access', 'user_id', 'user_access_id')->using('App\USER_ACCESS');
}
Logic
use App\User;
$user_id = Auth::user()->id;
//Get All Those Users Ids Which Does Not Belong To Auth User
$exception_user_ids = User::whereDoesntHave('users', function ($query) use($user_id) {
$query->where('user_id', $user_id);
})
->pluck('id');
The error may be in the User model.
The App\User model cannot belongsToMany() of itself...App\User.
I believe you may need a UserAccess model.
Try:
User Model
public function userAccess()
{
return $this->belongsToMany('App\UserAccess', 'user_access', 'user_id', 'user_access_id')
}
or try a hasMany relationship:
User Model
public function userAccess()
{
return $this->hasMany('App\UserAccess', 'user_id', 'id');
}
https://laravel.com/docs/7.x/eloquent-relationships#many-to-many
https://laravel.com/docs/7.x/eloquent-relationships#one-to-many

Laravel - User > Roles > Permissions within a Company

I am trying to describe a relationship between a User and a Company. More specific I want the following:
A User has one or Many Roles within a Company.
A Role has one or Many Permissions.
- users (id, name, surname, email, ...)
- permissions (id, name, label, ...)
- roles (id, name, label,...)
- companies (id, name, address, ...)
- permission_role (permission_id, role_id)
- user_role (user_id, role_id)
- company_user (company_id, user_id)
Anyone could help me out?
ER Diagram: https://prnt.sc/q4l614
The pivot_table name will be like user_role_company. Pivot table structure will be like
role_user Table
+---------+-----------+----------+-------------+
| id |user_id | role_id | company_id |
+---------+-----------+----------+-------------+
| 1 | 1 | 2 | 3 |
+---------+-----------+----------+-------------+
One User has one or many company id,
One User has also one or many role id,
One Role has belongs to many user
One Role has belongs to many company.
One Company has belongs to many user.
One Company has belongs to many role.
All of this scenario. you can implements scenario by this -
In User Model
class User extends Authenticatable
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function companyies()
{
return $this->belongsToMany(Company::class);
}
}
In Role Model -
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
public function companies()
{
return $this->belongsToMany(Company::class);
}
}
In Company Model -
class Company extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
Same as for Role and Permission.
You can check the relationship using Laravel tinker.
I Hope it will work for you.
you can read more details from this link : https://laravel.com/docs/6.x/eloquent-relationships#many-to-many

Laravel 5.8 Eloquent Model Relationship error

I have a relationship between two models, User and Follower.
User hasMany Follower, and Follower belongsTo User.
In my followers table in the database I have two columns, follower_id and following_id. Both these columns refer to the id column in the users table.
My follower and users table
followers
id
follower_id
following_id
users
id
name
username
User Model
public function followers(){
return $this->hasMany('App\Follower', 'follower_id');
}
public function followings(){
return $this->hasMany('App\Follower', 'following_id');
}
Follower Model
public function user(){
return $this->belongsTo('App\User');
}
In a test controller I am doing this:
$followed = Follower::find(2);
From here, I would like to select one of the columns, follower_id or following_id, and access the user that this particular row belongs to by using $followed->user->name. How would I go about that? Since I need to select a column before accessing, I am a little bit confused.
What can I do to access the data I need?
Your table should be :
followers
id
follower_id
following_id
user_id
users
id
name
username
In your Follower model :
public function user()
{
return $this->hasMany(Follower::class, 'user_id');
}
In your User model :
public function follower()
{
return $this->belongsTo(User::class, 'user_id');
}
Then you can query like this :
$follower = Follower::with('user')->findorFail(2);
$user_name = $follower->user->name;

Resources