Manage relation using Eloquemt ORM - laravel

I am working with Laravel5.4. I have a user table that have column like id,introducer_id,company_id,user_role.
If login user has company_id as 1 than fetch all users who has company_id as 1 and also fetch whose company is not same as login user but user_role is 3.
I need to fetch users as per the above requirement using Eloquent ORM. So how can I write query?

Do this:
User::where('company_id', auth()->user()->company_id)
->orWhere(function($q) {
$q->where('company_id', '<>', auth()->user()->company_id)
->where('user_role', 3);
})
->get();

Related

Mutli relationships with Eloquent and Laravel

I have 6 tables:
permissions:
id
permission_name
roles:
id
role_name
user_roles:
id
user_id
role_id
user_permissions:
id
user_id
permission_id
role_permissions:
id
role_id
permission_id
users:
id
username
email
Now I like to add a custom function into my Eloquent model for permissions named getUsersWithPermission().
Now it is possible that user has the permission by the role he has given (user table join on user_roles, join that table on role_permissions and last that table join on permissions.
Or the user has a specific permission set in the user_permissions table (join user_permissions table on user table and join the permissions table on the user_permissions table)
How can I create a Eloquent model function that returns all the users with a specific permission say: "notification.error.process" where that is the permission name
A hasMany doesn't quite do what I want (and I cannot define multi tables in there). I am using Laravel 5.6.
If you defined your many-to-many relations correctly (User-Permission and User-Role-Permission), the following should do the trick:
$permissionName = 'notification.error.process';
$usersWithPermission = User::whereHas('permissions', function($query) use ($permissionName) {
$query->whereName($permissionName);
})->orWhereHas('roles.permissions', function($query) use ($permissionName) {
$query->whereName($permissionName);
})->get();
Try to understand your table structure using this ER diagram.
TO handle this situation, You may create 3 'Eloquent Models'
User
Role
Permission
in every model you may create belongsToMany() relationship to each other models.
one example, On 'User Model'
public function permissions()
{
// need to define any other differences in your tables foreign keys as 2nd, 3rd parameters and so on.
return $this->belongsToMany(Permission::class);
}
Now you need to get all the users 'whom has a role which has the privilege' OR 'whom directly has the privilege.
to do so.
$users = User::whereHas('privileges', function($query) {
$query->where('permission_name', 'notification.error.process');
})->orWhereHas('roles.permissions', function($query) {
$query->where('permission_name', 'notification.error.process');
})->get();
I hope you will get an idea. your code may be slightly different from mine. but this is the concept.

laravel 5.6 how to get the number of msgs for all groups?

I have 3 tables:
users, groups, messages;
user table is the default table generated by php artisan make:auth, Groups table contain:
id, book_id
messages table contain:
id, group_id, from, msg_content
and there is many to many relation between users table and groups table, the pivot table conatain:
user_id, group_id, last_id_seen
now I want to get the groups that belongs to the user and the number of messages that belongs to each group and have id > last_id_seen in the following form:
group => number_of_messages_>_last_id_seen
I am new to Laravel so would you please help me to do this?
Use withCount():
$groups = Auth::user()->groups()->withCount(['messages' => function($query) {
$query->whereColumn('id', '>', 'last_id_seen');
}])->get();
foreach($groups as $group) {
// $group->messages_count
}

How to show all books not associated with a user. many-to-many relationship

I have 3 tables in my database. users, books and book_user.
book_user is the pivot table that manages the many-to-many relationship between users and books.
I have the Laravel relationship correctly setup and i am able to display all the books associated to a user using the following in Laravel.
$user = Auth::user();
return response()->json($user->books()->get());
Now i am trying to display all the books that are NOT associated to a particular user. I have been struggling for quite some time and cant seem to find anything that works. Any tips would be greatly appreciated.
If the book is not related to the user then you should not try to retrieve it via the user. Instead use the book model:
Book::whereDoesntHave('users', function ($q) {
$q->where('id', \Auth::id());
})->get();
If you want all books not belonging to any user at all, instead of all books not belonging to a particular user, you could do something like :
$books = Book::whereDoesntExists(function($query) {
$query->select('book_user.id_book')
->from('book_user')
->where('book_user.id_book', '=', 'books.id');
// Assuming that the columns on the pivot table are 'id_book' and 'id_user' and the primary key is 'id' in the 'books' table.
});
Here you fetch all books that haven't their id in the book_user pivot table's id_book column. So basically, all books not belonging to any user.

Laravel eloquent query model with pivot

I have a user model with pivot table role_user.
In my user table I have a field 'active'.
And a user can have multiple roles which are saved in pivot table.
How can I pull all the users where active = 1 and where user has specific role in pivot table?
Try this. This assumes you have an eloquent relationship set up between users and roles. I've only used this type of query in a hasMany / belongsTo relationship, but I think it'll work in your example as well.
$users = User::where('active', 1)->whereHas('roles', function ($query) {
$query->where('role', 'foo');
})->get();
To filter users by role use whereHas() method:
User::whereHas('roles', function($q) use ($role) {
$q->where('role', $role);
})->where('active', 1)->get();

Update many records in a laravel relationship

I have 4 tables that I'm trying to work with in Laravel and I can't figure out how to use eloquent to execute a particular query. I want to update all orders that belong to a user (through product_id) and that have null payout_id.
This raw sql statement works but I'm not sure how to use eloquent for this..perhaps sync?
UPDATE order_items i JOIN products p on (i.product_id = p.id) SET i.payout_id = null where p.user_id = 3
User Model
Product Model
FK: user_id
Order Model
FK: product_id
FK: payout_id
Payout Model
I would really appreciate any help!
First define a function orders in User Model
public function orders()
{
return $this->hasManyThrough('Orders', 'Product','user_id','product_id');
}
User::where('id','=',$userid)->with(array('orders'=>function($query){
$query->where('payout_id','=',0)->update(array('payout_id'=>$updatevalue));
}))->first();
You need to create a model for your tables i and p, see http://laravel.com/docs/eloquent for full information on model creation.
In the model for i you would then create a relationship to p:
public function p()
{
return $this->('p','id','product_id');
}
You can then run your query as follows:
$results = i::with('p')
->where('user_id', '=', 3)
->update(array('payout_id' => null));

Resources