Laravel relationship filter by company_id - laravel

I am doing a laravel api with custom permissions feature.
This is my structure of tables:
User
id | email | password
Company
id | companyName
Permissions
id | name
User_has_permissions
user_id | company_id | permission_id
I am get the user and permissions with code below in model:
public function permissions() {
return $this->belongsToMany(Permission::class, 'user_has_permission', 'user_id', 'permission_id');
}
And in controller:
public function show($company_id, $user_id) {
//now I need return only permissions related with $company_id
return User::with(['permissions'])->find($User_id);
}
Now, I am need get the user and your permissions, but, only related by company_id.
Anyone have any idea how can I get this result?
Any idea is welcome.
Thanks a lot.

You can query with includes, by doing key value syntax as the parameter. In BelongsToMany, it inner joins with the pivot table, which would make it possible to add a condition on the comapny_id.
return User::with(['permissions' => function ($query) use ($company) {
$query->where('user_has_permission.company_id', $company->id);
}])->find($id);

Related

Laravel - Find value is available in relationship

I need to check if the given user_id, location_id, and sub_location_id is belongs to the user on user_locations table. Based on this I need to give login permission to the user for the specific site.
Currently, I have the written code like below. But, don't know how to check the condition.
User::select('id')->with('user_locations:location')->where('user_id',$request->user_id)->get();
I need to put these conditions
is user found and active?
if user active. Then find the given sub location is tagged for the user.
if sub location found, then is the sub location active?
Below are the table structure.
Users Table
id (PK, AI),
user_id (UQ),
password,
status, ("Y"=> Active, "N"=> Inactive)
//other fields
public function user_locations(): HasMany
{
return $this->hasMany(user_locations::class);
}
User_Locations Table
id (PK, AI),
user_id (FK),
location_id (FK),
sub_location_id (FK),
status ("Y"=> Active, "N"=> Inactive)
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
I think you need to check relation existing
You can try this way for find user model
User::select('id')
->with('user_locations:location')
->where('user_id',$request->user_id)
->where('status','Y')
->whereHas('user_locations', function ($q) use ($request) {
$q->where('user_locations.user_id', $request->user_id);
$q->where('user_locations.status', 'Y');
})
->get();
If you want just to check user existing you can try this
User::where('user_id',$request->user_id)
->where('status','Y')
->whereHas('user_locations', function ($q) use ($request) {
$q->where('user_locations.user_id', $request->user_id);
$q->where('user_locations.status', 'Y');
})
->exists();
You can read mode about this here

Laravel 5.2 Eloquent ORM to get data from 3 tables

I have the following tables. users, user_details and client_teams. Each user has one details and each user can have many teams. schema for users:
id, name, email,parent_user_id
user_details:
id, user_id, client_team_id
client_teams:
id, user_id, team_name,status
In user_model i have the following relations:
public function userDetails(){
return $this->belongsTo('App\Models\UserDetails','id','user_id');
}
public function clientTeamList(){
return $this->hasMany('App\Models\ClientTeams','user_id','id');
}
In user_details model i have the following relation:
public function clientMemberTeam(){
return $this->belongsTo('App\Models\ClientTeams','client_team_id');
}
I want to be show the list of users who have a specific team ID and created by a specific user. The query that i am using is this:
$userCollections=Users::where([
['users.status','!=','DELETE'],
['users.parent_user_id',$clientId],
['users.id','!=',$loginUser->id]
])
->with([
'userDetails'=>function($query) {
$query->where('client_team_id',1);
}
]);
This is giving me all records for this user, Whereas i want to match by client_team_id and user_id
You need to use whereHas and orWhereHas methods to put "where" conditions on your has queries.
Please look into https://laravel.com/docs/8.x/eloquent-relationships
$userCollections = Users::where([['users.status', '!=', 'DELETE'],
['users.parent_user_id', $clientId],['users.id', '!=', $loginUser->id]
])
->whereHas('userDetails' => function ($query) {
$query->where('client_team_id', 1);
})->get();

Laravel 5 updateOrCreate (or Delete)

I have a setup where, I have a user_roles table.
Then the administrator, will be able to update these, by adding new role, updating the name of an old role, and lastly delete.
------------------
| id | user_role |
| 1 | admin |
| 2 | role 1 |
| 3 | role 3 |
------------------
I tried to use this block of code to update, add, delete the roles
public function update(Request $request, $id){
$roles = Model::all();
foreach($roles as $role){
$role->delete();
}
foreach($request->role as $role){
$role = new Model;
$role->user_role = $role;
$role->save();
}
}
But in the users table, I have a user_role column that references to the id of the user_roles table, so whenever I use the above code, all rows will be deleted, then a new id will be created for the new rows inserted. So, when I go back to the list of users, their user_role column will return null, because each user has a non-existing user_role id.
Using updateOrCreate kind of solves my problem, when it comes to updating old row/s or creating new row/s but the problem is, deleting rows. It can't delete rows.
I need to delete the rows that are existing in the database, and missing in the request.
What would be the best way to do this ?
I have fixed this case using the id approach proposed by maslauskast # https://laracasts.com/discuss/channels/laravel/updateorcreate-rows-from-a-csv-or-delete-if-not-on-the-csv?page=0
In your case a solution* will be
public function update(Request $request, $id){
$usersRoleToDelete = Model::all()->pluck('id', 'id');
foreach($request->role as $role) {
$createdOrUpdated = Model::createOrUpdate(['user_role' => $role]);
if (!empty($usersRoleToDelete[$createdOrUpdated->id])) {
unset($usersRoleToDelete[$createdOrUpdated->id]);
}
}
if (count($usersRoleToDelete)) {
Model::whereRaw(sprintf('id IN (%s)', implode(',', $usersRoleToDelete)))->delete();
/* Alternatively you could use
* Model::whereIn('id', $usersRoleToDelete)->delete();
* if the amount of ids is smaller than the maximum PDO arguments allowed
*/
}
}
Please note that I have not tested this.
this is my working updateOrCreate method based on Adrian answer in Laravel 5.3
public function update($id, Request $request)
{
$et=Model::find($id);
//update some parent table field's (if you want)
$et['type']=$request['type'];
$et['sum'] =preg_replace('/[^0-9]/s', '', $request['sum']); //for remove thousand separtor
$et->save();
$et_det=$et->et_dets()
->pluck('id','id'); // one-to-many relation
for ($i=0;$i<count($request['det_id']);$i++)
{//some matching condition
$createdOrUpdated = Model_dets::updateOrCreate(
[
'parent_id'=>$id,
'total'=>$request['total'][$i]
],
[
'columnA' => $request['columnA'][$i],
'ColumnB' => $request['ColumnB'][$i])
]);
if (!empty($et_det[$createdOrUpdated->id])) {
unset($et_det[$createdOrUpdated->id]);
}
}
if (count($et_det)) {
Model_det::whereIn('id', $et_det)->delete();
}
return Redirect::to('index')->with('alert-success','Update successfully');
}

Laravel 5 get name based on ID

I have a users and departments table. So my departments table might have a row like so
id | departmentName
----------------------
2 | Marketing
----------------------
And the users table might have something like
id | name | email | departmentId
-------------------------------------------------------
18 | Nick | nick#email.com | 2
-------------------------------------------------------
So the users table links to the departments table via the id.
So now onto my UserController, in the index function, I do
public function index()
{
$users = User::all();
return view('users.index', compact('users'));
}
Now that will display everything within my users table.
My problem is, I do not want to display the departmentId. I want to display the departmentName which is linked to that departmentID. So in the above example, my users index page for that one row should show Marketing, not 2.
How would I go about doing this?
Thanks
You can use Eloquent Relationships. What you described in your question is a One-to-Many Relation, meaning a department can have many users, and each user belongs to a department. So you'll need to setup a model for your departments table (if you haven't done so already) and then define the relationship in your User model like so:
class User extends Model
{
public function department()
{
return $this->belongsTo('App\Department', 'departmentId');
}
}
You can then access the department details in your view via that relationship:
#foreach ($users as $user)
{{ $user->department->departmentName }}
#endforeach

How to get user's menu that has active modules in Laravel 4 with Eloquent?

I have tables to store user's menu like below:
Table: modules
id
name
status (will have values: active / inactive)
Table: menus
id
module_id
link
Table: menu_user
user_id
menu_id
join
Table: users
id
name
password
The relationship will be like:
[users]-<menu_user>-[menus]-[modules]
Modules has many Menus; and relationship between Users and Menus is many to many.
I only can get user's menu:
$data = User::with('menus')->where('id', 2);
Any how with Eloquent way that I want to have the users's menu where the modules has active status?
Another approach would be to come from the User end and use a nested relationship to the module, eg.
User::where('users.id', 1)
->with(array('menus.module' => function($query) {
$query->where('modules.status', '=', 'active');
})
)->get();
This is dependent on the following in the Models:
User
public function menus()
{
return $this->belongsToMany('Menu');
}
Menu
public function module(){
return $this->belongsTo('Module');
}
Module
public function menu(){
return $this->hasMany('Menu');
}
Glen

Resources