I have a Laravel application with two models: Post and User. Each Post belongs to a User, and I want to authorize actions on a Post based on a specific attribute of the User who owns the post.
For instance, I only want users who have the is_admin attribute set to true to be able to delete posts, regardless of who created the post.
Here’s my current setup:
User Models
namespace AppModels;
use IlluminateFoundationAuthUser as Authenticatable;
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password', 'is_admin',
];
public function posts()
{
return $this->hasMany(Post::class);
}
}
Post Model
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Post extends Model
{
protected $fillable = [
'title', 'content', 'user_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
}
The Policy
namespace AppPolicies;
use AppModelsUser;
use AppModelsPost;
class PostPolicy
{
public function delete(User $user, Post $post)
{
// Checking if the user is admin
return $user->is_admin;
}
}
Registered the policy in AuthServiceProvider
namespace AppProviders;
use AppModelsPost;
use AppPoliciesPostPolicy;
use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
Post::class => PostPolicy::class,
];
public function boot()
{
$this->registerPolicies();
}
}
The Post Controller
namespace AppHttpControllers;
use AppModelsPost;
use IlluminateHttpRequest;
class PostController extends Controller
{
public function destroy(Post $post)
{
$this->authorize('delete', $post);
$post->delete();
return redirect()->route('posts.index')->with('success', 'Post deleted successfully.');
}
}
Is this the correct way to use a policy to authorize actions based on a related model’s attribute?
Are there any best practices or improvements I can make to this setup?
Alaa Elalfi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.