1. Go to this page and download the library: Download mimachh/guardians library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mimachh / guardians example snippets
composer
php artisan vendor:publish --tag=guardians-config
php artisan migrate
'providers' => [
// Other service providers...
Mimachh\Guardians\GuardiansServiceProvider::class,
],
use Mimachh\Guardians\HasRoles;
class User extends Authenticatable
{
use HasRoles;
// other configuration
}
php artisan guardians:seed
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
// Define the many-to-many relationship with Role
public function roles()
{
return $this->belongsToMany(\Mimachh\Guardians\Models\Role::class, config('guardians.role_user_table'));
}
}
namespace Mimachh\Guardians\Models;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
// Define the many-to-many relationship with User
public function users()
{
return $this->belongsToMany(\App\Models\User::class, config('guardians.role_user_table'));
}
}
if ($user->hasRole('slug')) {
// User has the 'slug' role
}
namespace Mimachh\Guardians\Observers;
use App\Models\User;
use Mimachh\Guardians\Models\Role;
class UserObserver
{
public function created(User $user)
{
$defaultRoles = config('guardians.default_roles_attached');
foreach ($defaultRoles as $roleName) {
$role = Role::where('slug', $roleName)->first();
if ($role) {
$user->roles()->attach($role);
}
}
}
}
namespace Mimachh\Guardians;
use Illuminate\Support\ServiceProvider;
use App\Models\User;
use Mimachh\Guardians\Observers\UserObserver;
class GuardiansServiceProvider extends ServiceProvider
{
public function boot()
{
User::observe(UserObserver::class);
}
public function register()
{
// Register any bindings or services
}
}