Add this line to your composer.json
"jeroen-g/laravel-auth": "dev-master"
Then update Composer
composer update
Add the service provider in app/config/app.php
:
'JeroenG\LaravelAuth\LaravelAuthServiceProvider',
The last thing to do is to migrate to create the tables for the users, roles and permissions
php artisan migrate --package="jeroen-g/laravel-auth"
if(Auth::can('edit'))
{
// show a form to edit stuff.
}
if(Auth::is('Moderator'))
{
// Show a form to edit stuff, if the 'Moderator' role has the 'edit' permission.
}
To use this function, make sure to give a user the 'Admin' role.
Auth::isAdmin();
You could for example use this to create a filter that protects your backend.
Route::filter('auth.admin', function()
{
if ( ! Auth::isAdmin()) return Redirect::to('login');
});
Auth::allRoles();
Auth::allPermissions();
Auth::allUsers();
//Example of both optional parameter
Auth::allUsers('json', true);
Both accept two optional parameters, which is the format of the returned results: array, object or json. By default an array is returned. The second is a boolean, set this to true if you want to include trashed items.
Auth::giveRole('Member', 2);
Auth::givePermission('edit', 2);
In both cases the second parameter is the user id. This is optional, if none is passed, the id of the logged in user is used.
Auth::giveRolePermission('edit', 'Admin');
The first parameter is the permission, the second the role. To find out if a role has a certain permission, you could use the roleCan()
function.
Auth::roleCan('Admin', 'edit');
Auth::takeRole('Member', 2);
Auth::takePermission('edit', 2);
Auth::takeRolePermission('edit', 'Admin');
Auth::roleExists('Admin');
Auth::permissionExists('edit');
Auth::userExists(2);
All three functions accept a second parameter, true
or false
, which determines if the trashed entries will also be used (trashed entries are soft-deleted from the database, see below).
// Name, description, level (any number)
Auth::addRole('Admin', 'One Role To Rule Them All', 10);
// Name, description
Auth::addPermission('edit', 'Ability to edit stuff');
// Username, password, email
Auth::addUser('Jeroen', 'password123', 'jeroen@example.com');
Auth::deleteRole('Moderator');
Auth::deletePermission('edit', true);
Auth::deleteUser(2);
A second parameter is accepted on all three functions. This boolean states if the entry (role/perm/user) should be deleted with force (default set to false). Soft-deleted (so not with force) will be left out of every request to the database (unless otherwise stated). They can however be restored.