Currently my db tables are defined as below:
site_roles - Contains different roles
site_user_roles - Links Users to many roles
site_permission_modules - Contains different access levels [eg. view admin controls, ban users]
site_role_permissions - Links permission modules to roles
My models in laravel are correctly defined to query these many to many relations. In code I want to check if a user has a certain permission module linked to him.
For better understanding, here are my models as well:
User
public function SiteRoles()
{
return $this->belongsToMany('App\SiteRole', 'site_user_roles', 'users_id', 'site_roles_id');
}
SiteRole
public function Users()
{
return $this->belongsToMany('App\User', 'site_user_roles', 'site_roles_id', 'user_id');
}
public function SitePermissionModules()
{
return $this->belongsToMany('App\SitePermissionModule', 'site_role_permissions', 'site_roles_id', 'site_permission_modules_id');
}
SitePermissionModule
public function SiteRoles()
{
return $this->belongsToMany('App\SiteRole', 'site_role_permissions', 'site_permission_modules_id', 'site_roles_id');
}
Here is what I currently did:
Auth::User()->SiteRoles()->with('SitePermissionModules')->get()
The with() keyword retrieves a nested array of permissions associated with each role.
I need to check if the user has a specific permission module linked to him.
What would be the best laravel way to do this?
EDIT:
Basically I'm just asking what would be the best way to chain 2 many to many relationships.
Auth::User()->SiteRoles()->with(['SitePermissionModules' => function ($query) {
$query->where('site_role_permissions','=','admin');
//use where as per your requirment.
}])->get();
Querying Relaionship
Related
A user can have one whitelabel.
A whitelabel can have many users.
I have a pivot table with whitelabel_id, and user_id columns
I have both relationships set up using ->belongsToMany() (with the inverse).
I am using a pivot table because I don't have a whitelabel_id on the users table (and won't be putting one in) so its defined as a many-to-many, but really it's one-to-many. I just get the first() whitelabel as there'll only be one for each user.
With this in mind. How do I select * users with the currently authenticated user's whitelabel?
I have this, it works, but is this the "Laravel" way? I feel it's slightly over engineered and Laravel would have a shorthand method.
$user->when(auth()->user()->whitelabel->first(), function ($query) {
return
$query->whereIn('id', auth()->user()->whitelabel->first()->users->pluck('id'));
})
This checks if the auth user has a whitelabel, and then gets all users with the same whitelabel.
Does Laravel have a quick shorthand for this?
Models:
class Whitelabel
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
class User
{
public function whitelabels()
{
return $this->belongsToMany(Whitelabel::class);
}
}
you can retrieve records for simple
$user = User::find(Auth::id())
$user->whitelabels
if you want return all user in Auth user's whitelabel
foreach($user->whitelabels as $whitelabel){
$whitelabel->users
}
I have a many to many relationship for users and roles. A user can have multiple roles, but I only want with to grab the FIRST role.
Consider the following code:
User::with('roles')->get()
Works great for all roles, but I only want the first role.
I've set this up in my model but doesn't work:
public function role()
{
return $this->roles()->first();
}
How do I load with for only the first result?
You should be able to call first directly on the eager loaded relationship like this:
User::with(['roles' => function ($query) {
$query->first();
})->get();
first() actually executes the query and returns the results as a collection. Relationships must return a query builder, which can then be chained or executed, so using first() in a relationship won't work.
UPDATE
I realised you want to use role in with, so you need to create a relationship to do that. Create a new relationship on your User model (you can use any limit described in the docs, not just oldest()):
public function role()
{
return $this->hasOne('App\Role')->oldest();
}
And then you can use it in with:
$users = User::with('role')->get();
I would like to create a Laravel Authorisation Policy, however rather than checking the user->id I would like to check the related users Business model (like $user->business()->id)
I've tried using the following in my OrderPolicy but it does not work.
OrderPolicy
class OrderPolicy
{
....
public function edit(User $user, Order $order)
{
if ($user->business()->id === $order->business_id) {
return true;
}
}
}
Blade
...
#can('edit', $business->orders())
Edit Link
#endcan
...
Could someone show me how I could do this correctly?
Assuming business() is a relationship method.
$user->business->id would be the id of the Business model that is related to the user.
May want to check that ->business isn't null first.
You can also query directly on the relationship if you don't want to load that relationship. $user->business()->where('id', $order->business_id)->exists()
Laravel 5.4 Docs - Eloquent - Relationships - Relationship Methods vs Dynamic Properties
I have three tables.
Users: id,name
Courses: id,user_id,name
Order: id,user_id,course_id (
Pivot table)
How can i make sure in course view that this user has purchased this particular course using Laravel eloquent.
Firstly, you need to define a many to many relationship between your models:
class User extends Model {
public function courses() {
return $this->belongsToMany(Course::class);
}
}
Once you have it, you can easily check if User has bought access to a Course with given ID with:
if ($user->courses()->find($courseId)) {
// user has access to course with given $courseId
}
If you simply want to an error to be raised when course was not bought, replace a call to find() with a call to findOrFail():
if ($user->courses()->findOrFail($courseId)) {
// user has access to course with given $courseId
}
The Laravel docs seem to indicate that the hasManyThrough declaration can only be used for relationships that are two levels "deep". What about more complex relationships? For example, a User has many Subjects, each of which has many Decks, each of which has many Cards. It's simple to get all Decks belonging to a User using the hasManyThrough declaration, but what about all Cards belonging to a User?
I created a HasManyThrough relationship with unlimited levels: Repository on GitHub
After the installation, you can use it like this:
class User extends Model {
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function cards() {
return $this->hasManyDeep(Card::class, [Subject::class, Deck::class]);
}
}
As stated in the comments, hasManyThrough doesn't support this level of specificity. One of the things you can do is return a query builder instance going the opposite direction:
//App\User;
public function cards()
{
Card::whereHas('decks', function($q){
return $q->whereHas('subjects', function($q){
return $q->where('user_id', $this->id);
});
});
}
We're going from Cards -> Decks -> Subjects. The subjects should have a user_id column that we can then latch onto.
When called from the user model, it would be done thussly:
$user->cards()->get();
Well, actually the best solution will be put the extra column to Card table - user_id, if you have so frequent needs to get all cards for the user.
Laravel provides Has-Many-Through relations for 2-depth relation because this is very widely often used relation.
For the relations Laravel does not support, you need to figure out the best table relationship yourself.
Any way, for your purpose, you can use following code snap to grab all cards for the user, with your current relation model.
Assumption
User has hasManyThough relationship to Deck,
So Project model will have following code:
public function decks()
{
return $this->hasManyThrough('Deck', 'Subject');
}
Deck has hasMany relationship to Card
Code
$deck_with_cards = $user->decks()->with("cards")->get();
$cards = [];
foreach($deck_with_cards AS $deck) {
foreach ($deck->cards as $c) {
$cards[] = $c->toArray();
}
}
Now $cards has all cards for the $user.