If you are using Spatie Permission package, you can use the middleware to check if the user has the required role to access a specific route. In this case, you don't need to define policies for each controller function. However, if you want to add more complex authorization logic, you can use policies in addition to the middleware.
For example, you can define a policy to check if a user can update a specific resource based on some conditions. Then, you can use the authorize method in your controller function to check if the user is authorized to perform the action.
Here's an example of how to use policies with Spatie Permission package:
- Define a policy for a specific model:
namespace App\Policies;
use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class PostPolicy
{
use HandlesAuthorization;
public function update(User $user, Post $post)
{
return $user->hasRole('admin') || $user->id === $post->user_id;
}
}
- Register the policy in the
AuthServiceProvider:
namespace App\Providers;
use App\Models\Post;
use App\Policies\PostPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
Post::class => PostPolicy::class,
];
public function boot()
{
$this->registerPolicies();
}
}
- Use the policy in your controller function:
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);
// Update the post
}
}
In this example, the update method in the PostController checks if the user is authorized to update the post using the authorize method. The update method in the PostPolicy defines the authorization logic based on the user's role and the post's owner.