PHP code example of lazycode / laravel-simple-permissions

1. Go to this page and download the library: Download lazycode/laravel-simple-permissions 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/ */

    

lazycode / laravel-simple-permissions example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Lazycode\Permissions\Traits\HasRolesAndPermissions; // Ensure this is correct

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRolesAndPermissions;

    // Your existing model code...
}


$user = User::find(1); // Replace with the appropriate user ID
$user->assignRole('Admin');

$role = $user->getRole();

if ($user->hasPermission('edit-user')) {
    // The user has permission to edit a user
}

IN blade.php

@hasPermission('edit-user')
    {{ show the content if user has this permission }}
@endhasPermission

use Illuminate\Database\Seeder;
use Lazycode\Permissions\Models\Role;
use Lazycode\Permissions\Models\Permission;
use App\Models\User;

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        // Create permissions
        $editUserPermission = Permission::create(['name' => 'edit-user']);
        $addUserPermission = Permission::create(['name' => 'add-user']);
        $deleteUserPermission = Permission::create(['name' => 'delete-user']);

        // Create a role
        $adminRole = Role::create(['name' => 'Admin']);

        // Attach permissions to the role
        $adminRole->permissions()->attach([$editUserPermission->id, $addUserPermission->id, $deleteUserPermission->id]);

        // Create a user and assign the role
        $user = User::create(['name' => 'Admin User', 'email' => '[email protected]', 'password' => bcrypt('password')]);
        $user->assignRole('Admin');
    }
}
bash
php artisan vendor:publish --provider="Lazycode\Permissions\PermissionsServiceProvider" --tag=config
bash
php artisan migrate