Last active
January 8, 2020 11:07
-
-
Save Gummibeer/0ad29d4cccff191534219d359ce55396 to your computer and use it in GitHub Desktop.
Car-User-Role permission scratch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class CarPolicy | |
{ | |
/* $user->can('drive', $car); */ | |
public function drive(User $user, Car $car) | |
{ | |
return $car->drivers->contains('id', $user->getKey()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Role extends Model | |
{ | |
public static function driver() | |
{ | |
return static::where('name', 'driver')->firstOrFail(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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