CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

24 April, 2021

Two Best Laravel Packages to Manage Roles Permissions

 Programing Coderfunda     April 24, 2021     Packages, php     No comments   

 

Two Best Laravel Packages to Manage Roles Permissions

Roles and permissions are an important part of many web applications. Laravel historically had a lot of packages for them, and improved the core code as well. So what is the situation on this market today? What packages are the best to use? I’ve picked two.

Why Do You Need Packages?

Let’s start from the beginning—Laravel has its own core logic for managing permissions. It was introduced in version 5.1.11 and has remained almost unchanged since. There we have things like:

  • Gates and Policies
  • $this->authorize() method
  • @can and @cannot Blade commands

One might say it’s enough to have Laravel core and there’s no need for packages. This is part of the reason older packages are abandoned; core functions replaced them.

But there’s still an area where packages can help—to manage the permissions and roles, which is not easy in the core. And there are two packages which do that really well and are actively maintained:

  • Laravel-permission by Spatie
  • Bouncer by Joseph Silber

Special mention: santigarcor/laratrust, which is a fork of unmaintained Entrust, and could be a strong third contestant. The problem with Laratrust is it replaces default Laravel commands with its own, so you wouldn’t be able to use Gates or @can syntax. Instead, you would need to use $user->can(‘edit-user’) or @permission Blade command. But if you don’t care about those extra syntax pieces, Laratrust is a great package. It also has Teams functionality, which is not present in Spatie’s or Bouncer packages.

There are a few more options, but they seem outdated and not that active. Still, you may want to watch them for a potential comeback:

  • Zizaco / entrust
  • Romanbican / roles
  • Kodeine / Laravel-acl

Now, let’s get deeper into a “battle review” between two main contestants.

What Do These Packages Actually Do?

They give you an API to deal with roles and permissions more easily. Also, the final code is more reader-friendly and easier to understand.

Instead of creating all rules in Policies and Gates, which would be fragmented in a few different places, you would have code like this:

$user->givePermissionTo('edit articles'); // Spatie package
$user->allow('ban-users'); // Bouncer package

Essentially, those two packages offer really similar functionality, with slightly different syntax and database structure. Let’s dig deeper and compare.

Installation and Usage

Both packages are installed similarly:

  • Add to composer and install.
  • Add a provider and facade (Bouncer) to config/app.php.
  • Publish and run migrations.
  • Add a special trait into User model (both packages use Traits).
  • That’s it; use package’s methods (optionally including its classes where needed).

Packages assume you already have a default Laravel users DB table, but don’t have any structure for roles/permissions. They will add their own tables and fields.

Both packages have clear documentation, and there were no issues whatsoever. Great job done on README files!

Database Structure

This is where the packages are quite different. Spatie’s package has these tables:

Two Best Laravel Packages to Manage Roles Permissions

Some explanations here:

  • Field guard_name has default value web**—**package allows to use multiple guards.
  • As you can see, there are two pivot tables for permissions—one with roles, and one with users.
  • Field model_type has default value App\User so there’s no direct foreign key to users table, no other table has user_id field.

Now let’s look at Bouncer’s database:

Two Best Laravel Packages to Manage Roles Permissions

Quite different, isn’t it? And even fewer relationships. Now, let me explain:

  • What Spatie calls “permissions,” Bouncer calls “abilities.” And then the “permissions” table is a set of abilities attached to an “entity.”
  • “Entity” (in all tables) is an object to assign abilities to. It may be a role or a user. Therefore, there is no direct relationship to user_id or users table; the same as with Spatie’s package.
  • There are a few more fields different from the previous package: abilities.title, abilities.only_owned, and roles.level. They add some additional functionality, but it is not well explained in the README file.
  • Spatie has guard fields which are not present in Bouncer.

All in all, Bouncer’s database structure seems a little more complicated and more difficult to understand at first, but with that comes a little more flexibility.

Available Methods

These packages do offer really similar functionality, so let’s compare in details.

Create Roles/Permissions/Abilities

Spatie

You can use facades of the package as normal facades of Laravel:

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

Role::create(['name' => 'writer']);

Permission::create(['name' => 'edit articles']);

Bouncer

You can create role and ability, and assignment all in one sentence:

Bouncer::allow('admin')->to('ban-users');

That’s it. Behind the scenes, Bouncer will create a Role model and an Ability model for you.

But you can also work with facades, too:

use Silber\Bouncer\Database\Ability;
Ability::create(['name' => 'edit articles']);

As you can see, Bouncer has a little more functionality here with automatic “behind the scenes” model creation.

Assigning Roles to a User

Spatie

$user->assignRole('writer');
$user->assignRole(['writer', 'admin']);

$user->removeRole('writer');

Roles can also be synced:

// All current roles will be removed from the user and replace by the array given
$user->syncRoles(['writer', 'admin']);

Bouncer

$user->assign('admin');
$user->assign(['writer', 'admin']);

$user->retract('admin');

It’s great that both packages accept either individual roles or arrays.

But Spatie’s package wins here because of syncRoles functionality. It’s really useful; with Bouncer you need to perform it manually with a few operations.

Assigning Permissions/Abilities to a User

Spatie

$user->givePermissionTo('edit articles');
$user->givePermissionTo('edit articles', 'delete articles');

$user->revokePermissionTo('edit articles');

Bouncer

$user->allow('ban-users');
$user->allow(['ban-users', 'edit-articles']);

You can pass the model name as a second argument.

Bouncer::allow($user)->to('edit', Post::class);
Bouncer::allow($user)->to('edit', $post);

$user->disallow('ban-users');
Bouncer::disallow($user)->to('delete', Post::class);

Similar functionality, but Bouncer offers the ability to pass the model class or its instance.

Checking Permissions/Roles for a User

Spatie

Check roles

$user->hasRole('writer');
$user->hasAnyRole(Role::all());
$user->hasAllRoles(Role::all());

Check permissions

$user->can('edit articles');
$role->hasPermissionTo('edit articles');

Bouncer

Check roles

$user->isAn('admin');
$user->isA('subscriber', 'editor');
$user->isAll('editor', 'moderator');
$user->isNot('subscriber', 'moderator');

Check permissions

Bouncer::allows('edit articles')

This section is pretty similar in both packages, with no clear winner.

Blade Commands

Spatie

@role('writer')
I'm a writer!
@else
I'm not a writer...
@endrole

@hasanyrole('writer|admin')
I have one or more of these roles!
@else
I have none of these roles...
@endhasanyrole

Bouncer

Bouncer does not add its own Blade directives.

More functionality by Spatie’s package. Of course, with both packages you can use default Laravel commands like @can and @endcan.

Caching

Spatie

Role and permission data is automatically cached to speed up performance.

To manually reset the cache for this package, run:

php artisan cache:forget spatie.permission.cache

Bouncer

All queries executed by the bouncer are cached for the current request. If you enable cross-request caching, the cache will persist across different requests.

Whenever you need, you can fully refresh the bouncer’s cache:

Bouncer::refresh();

Alternatively, you can refresh the cache only for a specific user:

Bouncer::refreshFor($user);

Caching is a little more robust in Bouncer. Enabling/disabling cache is a good thing, and refreshing the cache for a particular user might come handy.

Overall Conclusion

If you still expect a clear winner here, it’s not going to happen. Both packages are really good, and it’s a matter of preference.

Both of them have advantages in some functionality, but it’s more about the details.

Spatie’s Advantages:

  • A little better documentation (some Bouncer’s methods aren’t mentioned in README)
  • A little more understandable DB structure
  • syncRoles() method instead of delete-insert way
  • A few blade commands – @role and @hasanyrole
  • Ability to use multiple guards

Bouncer’s Advantages:

  • Create role/ability and assign it—all in one sentence
  • Allow or disallow permission based on model or its instance
    • A little better caching mechanism
    • A little more robust DB structure with a few more useful fields

If any of these details are really important to you, that could be the reason for your choice. Otherwise, pick Spatie or Bouncer, and you shouldn’t be disappointed.

P.S. Bonus Gift

Finally, both packages offer a set of functions to manage roles and permissions but don’t have any UI or admin panel to manage it. I’ve prepared a UI starter kit, based on both packages. You can use it as a boilerplate to manage roles and permissions.

Here are links to the GitHub repositories:

  • Laravel 5.4 admin panel based on Spatie Laravel-permission
  • Laravel 5.4 admin panel based on Bouncer
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Track Laravel Model Changes with Laravel Auditing

 Programing Coderfunda     April 24, 2021     Packages, php     No comments   


Track Laravel Model Changes with Laravel Auditing


Laravel Auditing is a Laravel package that aims to make it easy to track eloquent model changes. The documentation describes Laravel Auditing as follows:

This package will help you understand changes in your Eloquent models, by providing information about possible discrepancies and anomalies that could indicate business concerns or suspect activities.

Laravel Auditing allows you to keep a history of model changes by simply using a trait. Retrieving the audited data is straightforward, making it possible to display it in various ways.

Along with model changes, each audit record contains the User Agent, audit URL, and the IP address of the user. One of the main use-cases of the package is looking at suspicious activities or unexpected changes in the model.

Model Diffs with the Laravel Auditing Package

In my opinion, another use-case for this package could be providing versioning for records, such as blog posts or other content that allows you to see who changed what on a model easily. This could be used to perform auto-saves, see what changed, who changed it and revert changes from a previous version.

Let’s say you have a Post model that holds articles. The following would be how you add auditing to posts when they are saved and updated:

<?php

namespace App;

use OwenIt\Auditing\Auditable;
use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Contracts\Auditable as AuditableContract;

class Post extends Model implements AuditableContract
{
use Auditable;

public function user()
{
return $this->belongsTo('App\User');
}
}


Although not included in the example above, you can also define with attributes that will be included in the audit with an $auditIncluded = []; property on the model.

With the example Post model, you could get the diffs for a post like so with the Laravel auditing package:

// PostsController with route model binding
use App\Post;

function show(Post $post)
{
$diff = $post->audits()->with('user')->get()->last();

return view('posts.show')
->withPost($post)
->withDiff($diff);
}

Here’s an example of how you could display the diffs in a Blade view:

@if($diff)
<h3>Post Changes</h3>

<div class="author-info">
<span class="byline">
Revision by <strong>{{ $diff->user->name }}</strong>
</span>
<span class="time-ago">
{{ \Carbon\Carbon::parse($diff->created_at)->diffForHumans() }}
</span>
</div>

@foreach($diff->getModified() as $field => $value)
<h3>{{ ucfirst($field) }}</h3>
<table class="diff">
<tr>
<td style="background: #ffe9e9" class="deleted-line">{{ $value["old"] }}</td>
<td style="background: #e9ffe9" class="added-line">{{ $value["new"] }}</td>
</tr>
</table>
@endforeach
@endif

The example above only displays the last diff, but you could provide functionality to select the revision number or loop through the entire version history. The audits come back as a collection allowing you to perform collection operations on audits like any other model. The documentation contains audit presentation documentation to give you more ideas on how to present audit changes and metadata.

One thing to note: when I started experimenting with the package I used php artisan tinker to try and create audits. By default, the Laravel auditing package doesn’t track changes to models from the consoles (including tinker). If you have console commands or scheduled commands making changes to models you might want to store audits from the console. You can modify this behavior by publishing and update the provided config with:

<?php

return [
// ...
'console' => true,
]

Lastly, the package allows customizations to the audit model, audit driver (the package ships with the Database audit driver), and customizations to audit transformations before data for an audit is stored.

Check out the documentation for more details on everything you can do with the Laravel auditing package. You can also see the source code on GitHub.


Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

BotMan 2.0 PHP Chatbot Framework

 Programing Coderfunda     April 24, 2021     Packages, php     No comments   

BotMan 2.0 PHP Chatbot Framework


BotMan is a framework agnostic PHP Chatbot framework designed to simplify the task of developing innovative bots for multiple messaging platforms, including Slack, Telegram, Microsoft Bot Framework, Nexmo, HipChat, Facebook Messenger, WeChat and many more.

BotMan 2.0 was released earlier this week with a bunch of improvements and exciting changes. From a project and code management perspective a couple of things happened:

  • BotMan and the various repositories around BotMan moved to the BotMan GitHub Organization instead of mpociot/botman.
  • Each Driver (Slack, Telegram, etc.) is contained in a separate repository outside of the BotMan core code
  • BotMan Studio bundles BotMan with the Laravel PHP Framework

Using the BotMan Chatbot Framework

On a basic level, a chat bot includes functionality to listen for messages, and respond to those messages. For example, if you ask your bot the weather, they might look up the weather from an API and then give you back the forecast.

Another way you can use BotMan is to listen for events. For example, you could greet a user when they join a channel or leave one.

From the Documentation, here’s how you can use BotMan from a web-accessible route in your application:

<?php

use BotMan\BotMan\BotMan;
use BotMan\BotMan\BotManFactory;

$config = [
// Your driver-specific configuration
];

// create an instance
$botman = BotManFactory::create($config);

// give the bot something to listen for.
$botman->hears('hello', function (BotMan $bot) {
$bot->reply('Hello yourself.');
});

// start listening
$botman->listen();

The above code is framework-agnostic, but the fluent API makes it simple to write a chatbot.

Advanced Topics

BotMan also supports advanced features, such as a middleware system, natural language processing (NLP), retrieving user information, and storage.

The middleware system has been expanded more in the 2.0 release, which allows you to hook into different parts of the ChatBot lifecycle. You could do powerful things like keep track of stats related to answered chats, and provide NLP on incoming messages. The available entry points for middleware are: sending, received, and heard.

Using the middleware, BotMan provides built-in support for the api.ai NLP service. Middleware makes your bots smarter and able to process more than just static text. A good example where this feature could be useful is the /remind feature, where you can use natural language to be reminded of something at a later time and date.

BotMan Studio

BotMan Studio—a packaged BotMan and Laravel application—provides testing tools, an out of the box web driver implementation, and additional tools like easier driver installation and configuration support.

BotMan studio can speed up development by providing a web driver implementation, which allows you to develop your chatbot locally and interact with it through a simple Vue.js chat widget, which lets you communicate with your bot without deploying it.

You can install drivers more easily with the artisan commands provided by BotMan studio:

# List available drivers
$ php artisan botman:list-drivers

# Install facebook
$ php artisan botman:install-driver facebook

You can create new BotMan projects with the BotMan installer in a similar way that you create new Laravel projects:

$ botman new weatherbot

Testing in BotMan Studio

The testing helpers in BotMan studio are slick! Here’s a simple example of the helpers provided:

/* @test */
$this->bot
->receives('Hi')
->assertReply('Hello!');

If you’ve used Laravel, you are familiar with the lovely testing helpers provided that make testing easier. Here’s a more complex conversation test example:

$this->bot
->receives('Hi')
->assertReplies([
'Hello!',
'Nice to meet you. What is your name?',
])->receives('BotMan')
->assertReply('BotMan, that is a beautifule name :-)');

The concept of how to test a chat bot feel foreign to me, but I am impressed with how elegant and straightforward the testing helpers make testing a chat bot!

New Features in 2.0

From the project’s changelog, here’s the gist of what’s new in BotMan 2.0:

  • Added ability to originate inline conversations.
  • Moved each driver into their own repository.
  • Facebook – Added support to send file and audio attachments.
  • Telegram – Added support to send file, audio and location attachments.
  • Added Kik driver.
  • Added custom Attachment classes.
  • Added support to listen for message service events.
  • Changed the way middleware works in BotMan.
  • Added support for Slack interactive menu messages.
  • Added Facebook Referral driver.
  • Allow replying to an existing thread for Slack drivers (#327).
  • Added loadDriver method to BotMan.
  • Added ability to use BotMan with a local socket.

Learn More

I am getting excited to write my chat bot! You can learn more by checking out the BotMan documentation and following the botman/botman GitHub project. You can also follow @botman_io and the creator @marcelpociot on Twitter.

![](https://laravelnews.s3.amazonaws.com/images/book.png)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts Home

Meta

Popular Posts

  • Sitaare Zameen Par Full Movie Review
     Here’s a  complete Vue.js tutorial for beginners to master level , structured in a progressive and simple way. It covers all essential topi...
  • Tailwindcss best practices for responsive design
    Tailwind CSS provides powerful utilities for responsive design out of the box. To use it effectively and maintain clean, scalable code, here...
  • Crawl and Index Your Website with Laravel Site Search
      Laravel Site Search   is a package by Spatie to create a full-text search index by crawling your site. You can think of it as a private Go...
  • Tailwind CSS Tutorial (Beginner to Master)
    Here's a simple and complete Tailwind CSS tutorial designed for students and beginners , progressing step-by-step from beginner to mast...
  • Is there a way to write a JavaScript program that enables you to Search Words in Multiple PDF Files?
    I need to create a simple program/system/application using JavaScript that enables a user to search a certain word in multiple scanned PDF f...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (69)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • July (4)
  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

Loading...

Laravel News

Loading...

Copyright © CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda