Laravel Basic
Laravel Form
Laravel Database
Laravel Advance
Policies in Laravel are classes that organize authorization logic around a particular model or resource.
They are similar to Gates, but while Gates are for simple checks, Policies are for model-based authorization (e.g., can a user update a specific post, delete a comment, or view a profile).
authorize() and @can.You can create a policy with Artisan:
php artisan make:policy PostPolicy --model=Post
PostPolicy → The name of the Policy class.--model=Post → Links the policy to the Post model.This will generate a file at: app/Policies/PostPolicy.php
namespace App\Policies;
use App\Models\User;
use App\Models\Post;
class PostPolicy
{
// Can the user view a post?
public function view(User $user, Post $post)
{
return true; // Anyone can view
}
// Can the user create posts?
public function create(User $user)
{
return $user->role === 'author';
}
// Can the user update a post?
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
// Can the user delete a post?
public function delete(User $user, Post $post)
{
return $user->id === $post->user_id;
}
}
App\Providers\AuthServiceProvider.AuthServiceProvider or define inside separate service providers.php artisan make:provider 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(): void
{
// Automatically registers policies
}
}
$this->authorize function check the condition. if its flase page redirect to 403
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class AuthController extends Controller
{
use AuthorizesRequests;
public function update(Request $request, Post $post)
{
$this->authorize('update', $post); // Uses PostPolicy
$post->update($request->all());
return redirect()->back()->with('success', 'Post updated');
}
}
@can('update', $post)
<a href="{{ route('posts.edit', $post) }}">Edit Post</a>
@endcan
@cannot('delete', $post)
<p>You cannot delete this post.</p>
@endcannot