I am trying to make a connection between teams and users.
Pretty much Latrust looks like an awesome package BUT some things I believe could be explained better.
Let's pick a team (say: team_id = 1):
$team = Team::where('id', $request->team_id)->first();
And let's pick our users from the team:
$roles = Role::get();
$users = User::whereRoleIs($roles->pluck('name')->toArray(), $team)->get()
This will result in the following:
{
"message": "ok",
"data": [
{
"id": 1,
"name": "niki",
"email": "niki#user.com",
"email_verified_at": null,
"created_at": "2021-07-12T11:29:09.000000Z",
"updated_at": "2021-07-12T11:29:09.000000Z",
"roles": [
{
"id": 3,
"name": "user",
"display_name": "User",
"description": "User",
"created_at": "2021-07-12T11:29:08.000000Z",
"updated_at": "2021-07-12T11:29:08.000000Z",
"pivot": {
"user_id": 1,
"role_id": 3,
"user_type": "App\\Models\\User"
}
},
{
"id": 4,
"name": "leader",
"display_name": "Leader",
"description": "Leader",
"created_at": "2021-07-12T11:29:08.000000Z",
"updated_at": "2021-07-12T11:29:08.000000Z",
"pivot": {
"user_id": 1,
"role_id": 4,
"user_type": "App\\Models\\User"
}
}
]
},
{
"id": 2,
"name": "konna",
"email": "konna#user.com",
"email_verified_at": null,
"created_at": "2021-07-12T11:29:09.000000Z",
"updated_at": "2021-07-12T11:29:09.000000Z",
"roles": [
{
"id": 3,
"name": "user",
"display_name": "User",
"description": "User",
"created_at": "2021-07-12T11:29:08.000000Z",
"updated_at": "2021-07-12T11:29:08.000000Z",
"pivot": {
"user_id": 2,
"role_id": 3,
"user_type": "App\\Models\\User"
}
},
{
"id": 3,
"name": "user",
"display_name": "User",
"description": "User",
"created_at": "2021-07-12T11:29:08.000000Z",
"updated_at": "2021-07-12T11:29:08.000000Z",
"pivot": {
"user_id": 2,
"role_id": 3,
"user_type": "App\\Models\\User"
}
}
]
}
]
}
This returns all the roles those two users have (both of them belong in the same team)
How can we pick ONLY the role that the user has inside the team?
I thought of the following:
Getting all the user records with the $users query and then picking the role of the user from there.
foreach ($users as $user){
$userArray[] = array_push($userArray, $user->name, $user->roles->first());
}
However, this will return the first() or last() role attached to the user which can be anything (especially when a user may belong to multiple teams with a different role attached to every team he attends).
So my question is, how can I show the role of a user inside a team?
I was thinking of:
$user->roles->where($team->id)
But this returns all the roles that are attached to the user and not the specific role that the user has on the team.
Any help is appreciated.
I'm not experienced in Laratrust, but i feel like i have the solution you are needing. If we explode the source code, we can see your UserTrait includes a Role relationship. Even more so, we can see that it includes the pivot for the Team model.
if (Config::get('laratrust.teams.enabled')) {
$roles->withPivot(Config::get('laratrust.foreign_keys.team'));
}
Combining that with the method wherePivot() that Laravel has, you would be able to do the following retrieving the user roles for a given team. Therefor you will retrieve all the roles if you use the condition, with the way Laratrust works, you can have multiple roles thou.
$rolesInTeam = $user->roles()->wherePivot(Config::get('laratrust.foreign_keys.team'), $team)->get();
Thank you #mrhn for your valuable input
My solution came in the following form:
$rolesInTeam[] = null;
$users = User::whereRoleIs($roles->pluck('name')->toArray(), $team)->get();
foreach ($users as $user){
$rolesInTeam[] = array_push($rolesInTeam,$user->roles()->wherePivotIn(Config::get('laratrust.foreign_keys.team'), $team)->get());
}
Which returns as a result:
null,
[
{
"id": 4,
"name": "leader",
"display_name": "Leader",
"description": "Leader",
"created_at": "2021-07-12T11:29:08.000000Z",
"updated_at": "2021-07-12T11:29:08.000000Z",
"pivot": {
"user_id": 1,
"role_id": 4,
"user_type": "App\\Models\\User"
}
}
],
2,
[
{
"id": 3,
"name": "user",
"display_name": "User",
"description": "User",
"created_at": "2021-07-12T11:29:08.000000Z",
"updated_at": "2021-07-12T11:29:08.000000Z",
"pivot": {
"user_id": 2,
"role_id": 3,
"user_type": "App\\Models\\User"
}
}
],
4,
[
{
"id": 3,
"name": "user",
"display_name": "User",
"description": "User",
"created_at": "2021-07-12T11:29:08.000000Z",
"updated_at": "2021-07-12T11:29:08.000000Z",
"pivot": {
"user_id": 5,
"role_id": 3,
"user_type": "App\\Models\\User"
}
}
],
6```
Related
I am having a problem that i really can not understand. I am getting users in laravel where the role of the user is an admin or either a user. So when I am calling the users with the user role i am getting this (what I want):
[ { "id": 8, "username": "user", "firstname": "user", "lastname": "user", "email": "user#test.com", "email_verified_at": null, "phone_number": 6282223, "role": "user", "companyID": 1, "companyRole": "employee", "logged_in": 0, "created_at": "2021-11-03T15:25:29.000000Z", "updated_at": "2021-11-03T15:25:29.000000Z" }, { "id": 9, "username": "manager", "firstname": "manager", "lastname": "manager", "email": "manager#test.com", "email_verified_at": null, "phone_number": 623423, "role": "user", "companyID": 1, "companyRole": "manager", "logged_in": 0, "created_at": "2021-11-03T15:25:29.000000Z", "updated_at": "2021-11-03T15:25:29.000000Z" } ]
But when I call users with the role admin I am getting this (what i dont want):
{ "2": { "id": 10, "username": "mo", "firstname": "moemm", "lastname": "hus", "email": "hus#test.com", "email_verified_at": null, "phone_number": 6283, "role": "admin", "companyID": 0, "companyRole": "admin", "logged_in": 0, "created_at": "2021-11-03T15:25:29.000000Z", "updated_at": "2021-11-03T15:25:29.000000Z" } }
I littarly have the sme code for both but the only thing that changes is that i am calling different roles
public function getAllUsers(Request $request){
$users = User::all()->where('role', 'user');
return $users;
}
public function getAllAdmins(Request $request){
$admins = User::all()->where('role', 'admin');
return $admins;
}
And this is my api route for the both functions:
Route::get('/admins', [UserController::class, 'getAllAdmins']);
Route::get('/users', [UserController::class, 'getAllUsers']);
I'm accessing a single model and loading its relation using this code below,
return Application::select('id')->with([
'oneApplicant:id,user_id,first_name,last_name,email',
'oneApplicant.referrer:id,parent_id,first_name,last_name,email',
'oneApplicant.referrer.parent:id,first_name,last_name,email',
])->find($id);
and the response is this
{
"id": 200,
"oneApplicant": [
{
"id": 200,
"userId": 9,
"firstName": "Mac",
"lastName": "Lebsack",
"email": "edicki#example.net",
"referrer": {
"id": 9,
"parentId": 5,
"firstName": "Aurelia",
"lastName": "Boyle",
"email": "uhirthe#example.org",
"parent": {
"id": 5,
"firstName": "Dewitt",
"lastName": "Bednar",
"email": "tluettgen#example.net"
}
}
}
]
}
I wanted to convert the response to something like this (couldn't care less about the other attribute, all I need is first_name, last_name & email )
[
{
"id": 200,
"userId": 9,
"firstName": "Mac",
"lastName": "Lebsack",
"email": "edicki#example.net",
},
{
"id": 9,
"parentId": 5,
"firstName": "Aurelia",
"lastName": "Boyle",
"email": "uhirthe#example.org"
},
{
"id": 5,
"firstName": "Dewitt",
"lastName": "Bednar",
"email": "tluettgen#example.net"
}
]
I was testing with map and transform but it doesn't even work and as I understand with the error, my result is not a collection.
Can someone guide me on how to achieve this,
Thanks
I am attempting to scope an answer to a User or Project via a polymorphic relationship via multiple levels but I am having some trouble getting my head around it.
It's tricky to explain, but I will show you what I have at the moment, minus the Answer model/relationship.
I have a Category and a Role model. These are in a belongsTo relationship (a role belongs to a category).
I also have a Question model, this also has a belongsTo relationship with a Role (a question belongs to a role).
I have created a roleables polymorphic relationship, allowing me to assign roles to either a User or a Project.
All of this is working as expected. I am able to return the assigned roles via my endpoint user/1/roles or project/1/roles, and in this endpoint, I am able to return the questions for that role (see example output below).
{
"data": [
{
"id": 20,
"name": "Actor",
"entity_id": 1,
"category_id": 3,
"questions": [
{
"id": 20,
"role_id": 20,
"field_type": "text",
"field_name": "Height",
"field_default_value": null,
"field_validation_rules": "required,string,max:5",
"field_options": false,
"order": 0
},
{
"id": 21,
"role_id": 20,
"field_type": "text",
"field_name": "Weight",
"field_default_value": null,
"field_validation_rules": "required,string,max:5",
"field_options": false,
"order": 1
},
{
"id": 22,
"role_id": 20,
"field_type": "select",
"field_name": "Race",
"field_default_value": null,
"field_validation_rules": "required,string,max:255",
"field_options": [
{
"id": "white",
"name": "White"
},
{
"id": "mixed",
"name": "Mixed"
}
],
"order": 2
},
{
"id": 23,
"role_id": 20,
"field_type": "select",
"field_name": "Gender",
"field_default_value": null,
"field_validation_rules": "required,string,max:255",
"field_options": [
{
"id": "male",
"name": "Male"
},
{
"id": "female",
"name": "Female"
},
{
"id": "other",
"name": "Other"
}
],
"order": 3
}
],
"created_at": {
"date": "2019-07-24 13:35:33.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"date": "2019-07-24 13:35:33.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"entity_type": "user"
},
{
"id": 23,
"name": "Singer",
"entity_id": 1,
"category_id": 3,
"questions": [
{
"id": 26,
"role_id": 23,
"field_type": "text",
"field_name": "Description",
"field_default_value": null,
"field_validation_rules": "required,string,max:255",
"field_options": false,
"order": 0
}
],
"created_at": {
"date": "2019-07-24 13:35:33.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"date": "2019-07-24 13:35:33.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"entity_type": "user"
},
{
"id": 32,
"name": "Console Operator",
"entity_id": 1,
"category_id": 5,
"questions": [
{
"id": 35,
"role_id": 32,
"field_type": "text",
"field_name": "Description",
"field_default_value": null,
"field_validation_rules": "required,string,max:255",
"field_options": false,
"order": 0
}
],
"created_at": {
"date": "2019-07-24 13:35:33.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"date": "2019-07-24 13:35:33.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"entity_type": "user"
},
{
"id": 60,
"name": "Composer",
"entity_id": 1,
"category_id": 7,
"questions": [
{
"id": 63,
"role_id": 60,
"field_type": "text",
"field_name": "Description",
"field_default_value": null,
"field_validation_rules": "required,string,max:255",
"field_options": false,
"order": 0
}
],
"created_at": {
"date": "2019-07-24 13:35:33.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"date": "2019-07-24 13:35:33.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"entity_type": "user"
}
]
}
The problem that I am trying to get my head around is Answers to the questions. Just a little background, which may help me explain this in writing:
In the front-end, I have a page in which the user can update their information, on this page they also have the ability to assign themselves some roles. When the click on a role the list of questions is displayed and they have the ability to answer them.
The same is also true for a Project. A user can create projects, and have the ability to assigned roles and answer the relevant questions.
So, I guess I will need to create a new table in the database to store the answers.
The question is how/what relationship should this new answers table have to the question, user/project in order to get all the roles, questions and any answers scoped to the entity (user/project) and it's roles?
I would love the each role in the output from my user/1/roleendpoint to look more like the following (notice the new answers key in questions):
{
"id": 60,
"name": "Composer",
"entity_id": 1,
"category_id": 7,
"questions": [
{
"id": 63,
"role_id": 60,
"field_type": "text",
"field_name": "Description",
"field_default_value": null,
"field_validation_rules": "required,string,max:255",
"field_options": false,
"order": 0,
"answers": { ... }
}
],
"created_at": {
"date": "2019-07-24 13:35:33.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"date": "2019-07-24 13:35:33.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"entity_type": "user"
}
I'm making a chat api in Laravel. I have three models. User Chat and Message and they have their respective tables.
user table
id|name|email|other fields
chat table
id|user_id|receiver_id
message table
id|chat_id|message|created_at|updated_at|
Result is:
{
"data": [
{
"id": 7,
"chat_id": 5,
"message": "User 2 to 1",
"created_at": "2019-02-01 11:32:29",
"updated_at": "2019-02-01 11:32:29",
"chat": null
},
{
"id": 6,
"chat_id": 1,
"message": "Sample Chat",
"created_at": "2019-02-01 10:09:22",
"updated_at": "2019-02-01 10:09:22",
"chat": {
"id": 1,
"user_id": 1,
"receiver_id": 1,
"created_at": "2019-02-01 09:41:59",
"updated_at": "2019-02-01 10:09:22"
}
},
{
"id": 2,
"chat_id": 1,
"message": "Sample Chat",
"created_at": "2019-02-01 09:42:34",
"updated_at": "2019-02-01 09:42:34",
"chat": {
"id": 1,
"user_id": 1,
"receiver_id": 1,
"created_at": "2019-02-01 09:41:59",
"updated_at": "2019-02-01 10:09:22"
}
},
{
"id": 1,
"chat_id": 1,
"message": "Sample Chat",
"created_at": "2019-02-01 09:41:59",
"updated_at": "2019-02-01 09:41:59",
"chat": {
"id": 1,
"user_id": 1,
"receiver_id": 1,
"created_at": "2019-02-01 09:41:59",
"updated_at": "2019-02-01 10:09:22"
}
}
]
}
I've tried
$messages = Message::with(['chat' => function($query) use($user){
$query->where('user_id', $user->id);
}])
->latest()
->get();
As you can see the first data chat model is null.
I expect to only get all the messages connected to user id from the chat model.
use whereHas in your query will give only that chat belongs to purticular user.
$messages = Message::with(['chat'])->whereHas('chat', function ($query) {
$query->where('user_id', $user->id);
})
->latest()
->get();
My table's fields are as below :
users : id email first_name last_name (rest are there but need only these)
activity_stream : id user_id post created_at updated_at deleted_at
activity_stream_comments : id post_id user_id comment created_at updated_at deleted_at
I need listing of all the users posts with related comments just like you see in facebook, it shows various users posts with posts comments so for now I basically need to list down all the users posts with related comments.
I am trying the below query but it gives only the post that have comments that too in different sets :
$results = DB::table('activity_stream')
->join('users', 'users.id', '=', 'activity_stream.user_id')
->join('activity_stream_comments', 'activity_stream.id', '=', 'activity_stream_comments.post_id')
->select('activity_stream.*', 'users.first_name','users.last_name', 'activity_stream_comments.comment')
/*->where('activity_stream.user_id', $user_id)*/
->whereNull('activity_stream.deleted_at')
->orderBy('activity_stream.created_at', 'desc')
->get();
return response()->json($results);
And the return is :
[
{
"id": "97",
"user_id": "30",
"post": "hi how are you?",
"created_at": "2015-11-20 04:35:11",
"updated_at": "2015-11-20 04:35:11",
"deleted_at": null,
"first_name": "Abhijan",
"last_name": "Pal",
"comment": "test"
},
{
"id": "14",
"user_id": "49",
"post": "Test Post",
"created_at": "2015-11-13 04:51:53",
"updated_at": "2015-11-13 04:51:53",
"deleted_at": null,
"first_name": "Nazir",
"last_name": "Hussain",
"comment": "This is my first comment"
},
{
"id": "14",
"user_id": "49",
"post": "Test Post",
"created_at": "2015-11-13 04:51:53",
"updated_at": "2015-11-13 04:51:53",
"deleted_at": null,
"first_name": "Nazir",
"last_name": "Hussain",
"comment": "This is my 2nd comment"
}
]
Improvement :
$results = User::with('activity_stream.activity_stream_comments')->find($user_id);
return response()->json($results);
While using relationship and using above query I get the response as below :
{
"id": "49",
"email": "nazir.2cool#gmail.com",
"permissions": null,
"last_login": "2015-11-19 09:32:36",
"first_name": "Nazir",
"last_name": "Hussain",
"created_at": "2015-11-03 12:36:56",
"updated_at": "2015-11-19 09:32:36",
"facebook_id": "1051400994880427",
"facebook_token": "CAAX3UySfMDcBAFs8glgjz9p1Qdt0M1zwRrmZB9y4WkEPOEldIM5BKVURut8pcg9ios6GiZBschXWBKCqM6HdyZCIxkih6Rwh2SSABrzAHZCzGZBqcISDIlUwnNp73zF8PEZAgXKdzhZAQtfjZAeawUlAHTNpt2RyXTPoeH0ETj8jSclIxMSXPxfbDlnmNjoJXVwZD",
"facebook_profile_url": "",
"facebook_avatar": "https://graph.facebook.com/v2.5/1051400994880427/picture?width=1920",
"google_id": "112519651577038840839",
"google_token": "ya29.MQLD4wmUQSqGyMVENv8mrko-tvsqg3aLibdy5m-KWBp-HqP5liYB8GlWvSC4c1ZXka3YRRgA2dX40Q",
"google_profile_url": "https://plus.google.com/+NazirHussain91",
"google_avatar": "https://lh3.googleusercontent.com/-nLaXbUtBV0g/AAAAAAAAAAI/AAAAAAAAAAA/QaM3CzCJxlM/photo.jpg?sz=50",
"twitter_id": "832857385",
"twitter_token": "832857385-2PqAa48RffL2Yl7ZNJinBhIawMmH56amI54OBklR",
"twitter_profile_url": "",
"twitter_avatar": "http://pbs.twimg.com/profile_images/2626032008/hzd0ynsei7qjpyobaklw.jpeg",
"role": "author",
"activity_stream": [
{
"id": "14",
"user_id": "49",
"post": "Test Post",
"created_at": "2015-11-13 04:51:53",
"updated_at": "2015-11-13 04:51:53",
"deleted_at": null,
"activity_stream_comments": [
{
"id": "1",
"post_id": "14",
"user_id": "49",
"comment": "This is my first comment",
"created_at": "2015-11-19 10:49:13",
"updated_at": "2015-11-19 10:49:13",
"deleted_at": null
},
{
"id": "2",
"post_id": "14",
"user_id": "49",
"comment": "This is my second comment that I edited as well",
"created_at": "2015-11-19 11:03:01",
"updated_at": "2015-11-20 11:35:04",
"deleted_at": null
},
{
"id": "6",
"post_id": "14",
"user_id": "30",
"comment": "This is another test comment",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00",
"deleted_at": null
}
]
},
{
"id": "24",
"user_id": "49",
"post": "This is my first post",
"created_at": "2015-11-13 06:23:24",
"updated_at": "2015-11-13 06:23:24",
"deleted_at": null,
"activity_stream_comments": []
}
]
}
Now there are two questions : 1. How to use orderBy and 2. In the post and comment level how to get user name along with user id at the same time because querying again is not at all a good idea.