Skip to content

Instantly share code, notes, and snippets.

@Gummibeer
Last active January 8, 2020 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gummibeer/0ad29d4cccff191534219d359ce55396 to your computer and use it in GitHub Desktop.
Save Gummibeer/0ad29d4cccff191534219d359ce55396 to your computer and use it in GitHub Desktop.
Car-User-Role permission scratch
<?php
class Car extends Model
{
public function users()
{
return $this->belongsToMany(User::class, 'car_user_role')
->using(CarUserRole::class)
->withPivot('role_id', 'user_id', 'car_id');
}
public function drivers()
{
return $this->users()->wherePivot('role_id', Role::driver());
}
}
<?php
class CarPolicy
{
/* $user->can('drive', $car); */
public function drive(User $user, Car $car)
{
return $car->drivers->contains('id', $user->getKey());
}
}
<?php
class CarUserRole extends Pivot
{
public function car()
{
return $this->belongsTo(Car::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function role()
{
return $this->belongsTo(Role::class);
}
}
<?php
class Role extends Model
{
public static function driver()
{
return static::where('name', 'driver')->firstOrFail();
}
}
<?php
class User extends Model
{
public function cars()
{
return $this->belongsToMany(Car::class, 'car_user_role')
->using(CarUserRole::class)
->withPivot('role_id', 'user_id', 'car_id');
}
public function drivenCars()
{
return $this->cars()->wherePivot('role_id', Role::driver());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment