I started to learn laravel 1 month ago and I have the next issue.
I have 2 models, user and role and they have M to N relationship, therefore I have 3 tables.
Class Role Class Role_User Class User
=========== =============== ===========
id | name id | user_id | role_id id | name | lastname
1 ADMIN 1 1 1 1 John Rambo
2 AUTOR 2 1 2
3 USER
In the models I have the next code
Model User
public function roles()
{
return $this->belongsToMany(Role::class, 'role_user');
}
Model Role
public function users()
{
return $this->belongsToMany(User::class);
}
I need in my view to list all user with role ADMIN and I dont know waht code I need to put.
public function index($type)
{
$users = Role::all()->roles()->where('name', 'ADMIN');
return view('admin.user.list', compact('users'));
}
Could you help me pls?
Since you want a result composed of users, you need to launch your query on them. And dont forget to run the query with get() (this case), first(), find(..)....
$users = User::whereHas('roles', function ($role) {
$role->where('name','ADMIN');
})->get();
return view('admin.user.list', compact('users'));
Related
I have 3 models: User, Post and Comment.
The relationships are set up like so:
User Model:
public function posts()
{
return $this->hasMany(Post::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
Post Model:
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->belongsToMany(Comment::class);
}
Comment Model:
public function user()
{
return $this->belongsTo(User::class);
}
public function posts()
{
return $this->belongsToMany(Post::class);
}
And there is the comment_post pivot table (Which does not have a pivot Model - Do I need it in my case?)
Given a post_id, how can I get all the comments that belongs to it in the pivot table, for example:
comment_id | post_id
-----------|--------
1 | 1
2 | 2
3 | 3
4 | 4
5 | 1
If I want to get all the comments that belong to post with post_id 1, which would result in comments 1 and 5 - how can I achieve that? Nothing I tried work.
I've tried adding withPivot to the relationship, and then wherePivot to the query, tried defining the post_id and comment_id explicitly in the relationship, for example:
$comments = Comment::with(['posts' => function ($query) use ($comment_id) {
$query->wherePivot('post_id', $post_id);
}])->get();
It just doesn't work.
I either get all the comments, or I get Unknown column 'pivot' in 'where clause'
Don't trouble yourself with not needed complexity. Simply use your defined relationships to do so:
Post::find(1)->comments;
And you don't need a model for your pivot table in this case.
You can't access pivot table with wherePivot in the query. I don't have any specific idea about the way you're trying to do the job. But mainly, you have to specify your desired data. If you want the comments of 'a' post, you have to find the post and get the comments related to that post. Your way is getting all the comments and their posts and check if the id of the post is the same as your desired post_id. This way is too complicated and have redundunt data and can be logically incorrect.
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();
I'm not sure how to phrase this question, but I need to do the following:
I have a pivot table with three columns user_id, account_id, role_id
So in my database if I have these rows on account_role_user (pivot)
|---------------------|------------------|-------------
| account_id | user_id | role_id |
|---------------------|------------------|-------------
| 1 | 1 | 1 |
|---------------------|--------------------------------
| 2 | 2 | 1 |
------------------------------------------------------
| 1 | 2 | 3 |
------------------------------------------------------
Role - 1 = owner
Role - 3 = manager
What I'm trying to do is get users on a specific account with their specific role. But I'm only able to query things like App\User::with('accounts.roles')->whereId(2)->first(); which does show the users on an account, but it groups their roles that aren't specific to the account.
I only want the users and their roles that are relevant to the account.
If I'm querying account with id of 1 and I want to list users on that account with their role, I should have something like:
$account = App\Account::find(1)
User with ID of 1 has a role id of 1 on the account id of 1
User with ID of 2 has a role id of 3 on the account id of 1
User Model:
public function accounts() {
return $this->belongsToMany('App\Account', 'account_role_user', 'user_id', 'account_id');
}
public function roles() {
return $this->belongsToMany('App\Role', 'account_role_user', 'user_id', 'role_id');
}
Account model:
public function users() {
return $this->belongsToMany('App\User', 'account_role_user', 'account_id', 'user_id');
}
public function roles() {
return $this->belongsToMany('App\Role', 'account_role_user', 'account_id', 'role_id');
}
Role Model:
public function users() {
return $this->belongsToMany('App\User', 'account_role_user', 'role_id', 'user_id');
}
public function accounts() {
return $this->belongsToMany('App\Account', 'account_role_user', 'role_id', 'account_id');
}
Thanks to someone's help on Laravel's Discord channel, I figured this out.
On the Account Model, I changed the users() relation to:
public function users() {
return $this->belongsToMany('App\User', 'account_role_user')
->using('App\AccountRoleUser')
->withPivot('role_id');
}
I created a pivot model called AccountRoleUser
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class AccountRoleUser extends Pivot
{
public function role() {
return $this->belongsTo('App\Role');
}
}
And on the User model, I changed the accounts() relation to:
public function accounts() {
return $this->belongsToMany(Account::class, 'account_role_user')->withPivot('role_id');
}
Now my query is really succinct and logical:
$account = auth()->user()->accounts->where('foo', 'bar')->first();
$users = $account->users;
Each User inside the collection has a pivot object now coming from the pivot model.
Which means I can now do something like:
#foreach ($users as $user)
<p>This is user {{ $user->first_name }} {{ $user->last_name }} with a role of
{{$user->pivot->role->description}}
</p>
#endforeach
I've a User model and a likes table. I applied polymorphic relation to it.
likes table has the following structure:
user_id --- likeable_id ---- likeable_type
eg: 1 ---- 5 ---- App\User //This indicates user 1 follows 5
eg: 3 ---- 1 ---- App\User //This indicates user 3 follows 1
Now I'm trying to get the followers and following list.
In the User model I added
public function likes()
{
return $this->morphMany(Like::class, 'likeable');
}
public function followers()
{
return $this->belongsTo('App\Like', 'likeable_id', 'user_id');
}
and from the controller, I've tried to do this:
$user1 = User::with('followers')->where('username', $username)->first();
But it's returning null for the followers relation. Am I doing it right?
Got the answer by myself: In User model -
public function followers()
{
return $this->morphMany('App\Like', 'likeable')->with('user');
}
public function following()
{
return $this->morphMany('App\Like', 'user', 'likeable_type')->with('user');
}
I've done this a lot of times but for some reason I can't seem to get it to work this time. I have users and they have permissions. I have a permissions table, users table, and a users_permissions table. The users_permissions table has a series of ids from the users table and series of permissions ids from the permissions table. .For example:
1, 1
1, 2
1, 3
2, 1
2, 3
and so on... Basically, I do a
$up = UserPermissions::where('user_id','=',$userid)->where('permission_id','=',$permissionid)->first();
$up->delete();
This gets it but I can just do a $up->delete() because the records don't have an id. Is there a way to do this without modifying my tables? Thanks!
Nick
Assuming your relationships are properly defined:
In User.php
class User extends Eloquent
{
public function permissions()
{
return $this->belongsToMany('UserPermission');
}
}
In UserPermission.php
class UserPermission extends Eloquent
{
public function users()
{
return $this->belongsToMany('User');
}
}
To remove permission with id $permissionid from user with id $userid you just need
User::find($userid)->permissions()->detach($permissionid);
To remove all permissions from user with id $userid
User::find($userid)->permissions()->detach();