Another great news for Laravel community – more and more often repeated functions become a part of Laravel framework itself. Today a new addition is Authorization or ACL functionality.
As usual, it was officially announced on Twitter – like this:
First announcement of today: a beautiful way to organize your ACL logic in Laravel. Available immediately! http://t.co/kKDOVWiWRO ?
— Laravel (@laravelphp) August 31, 2015
Already retweeted and favorited by hundreds of Laravel fans, this feature adds some new functionality to Auth mechanism. Here are just a few example from new official documentation:
New Gate facade:
if (Gate::forUser($user)->allows('update-post', $post)) { // }
Using User model in request:
if ($request->user()->can('update-post', $post)) { // ... Update post }
Blade helpers:
@can('update-post', $post) Edit Post @endcan
Form Request classes – in method authorize():
return Gate::allows('update', Post::findOrFail($postId));
Wrapping rules into Policy classes:
Artisan command:
php artisan make:policy PostPolicy
Policy Class function:
class PostPolicy { public function update(User $user, Post $post) { return $user->id === $post->user_id; } }
Personally, it reminds me a little of WordPress users/capabilities functions like current_user_can() and similar ones.
Important note – this new functionality was built not only by Taylor Otwell himself, but also by Adam Wathan – thanks for that, guys!
is it role based? Does this mean I can get rid of third-party packages like entrust completely?
Hardik, good question. It depends on your example of usage – maybe Entrust has something extra with Laravel ACL wouldn’t have. So I would advice to play with it and try for yourself.
Are any of you having troubles with setup? For some reason I am getting errors thrown at me about the interface not being instantiable. I followed the directions in the docs – is there an extra implied step that I’m missing?
Did you manage to resolve this, I am having the same issue.
I have a question, why does my update method always return false even when the right user is logged in.
Please help
class PostPolicy
{
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
}
John, try dd($user->id . ‘ ‘ . $post->user_id); inside the function before the return and you will see the real values