Post Policy

php artisan make:policy PostPolicy --model=Post

   INFO  Policy [app/Policies/PostPolicy.php] created successfully.

You have to fill this methods our to return a Boolean , true or false

*Expected type 'bool'. Found 'void'

    /**
     * Determine whether the user can view any models.
     */
    public function viewAny(User $user): bool
    {
        //
    }


<?php

namespace App\Policies;

use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\Response;

class PostPolicy
{
    /**
     * Determine whether the user can view any models.
     */
    public function viewAny(User $user): bool
    {
        return $user->role = "admin";  
    }

    /**
     * Determine whether the user can view the model.
     */
    public function view(User $user, Post $post): bool
    {
        return TRUE;
    }

    /**
     * Determine whether the user can create models.
     */
    public function create(User $user): bool
    {
        return $user->id > 0;
    }

    /**
     * Determine whether the user can update the model.
     */
    public function update(User $user, Post $post): bool
    {
        return $user->id == $post->user_id; 
    }

    /**
     * Determine whether the user can delete the model.
     */
    public function delete(User $user, Post $post): bool
    {
        return $user->id == $post->user_id; 
    }

    /**
     * Determine whether the user can restore the model.
     */
    public function restore(User $user, Post $post): bool
    {
        return $user->id == $post->user_id; 
    }

    /**
     * Determine whether the user can permanently delete the model.
     */
    public function forceDelete(User $user, Post $post): bool
    {
        return $user->role = "admin"; 
    }
}

 

if you need to check multipel criteria 

 

 /**
     * Determine whether the user can update the model.
     */
    public function update(User $user, Post $post): bool
    {

        // Check if user is the post author
        if ($user->email == 'butlerjraines@gmail.com') {
            return true;
        }

        // Check if user is the post author
        if ($user->id === $post->user_id) {
            return true;
        }

        return false;
    }

 

add it to app/Providers/AuthServiceProvider.php

 

<?php

namespace App\Providers;
use Illuminate\Support\Facades\Gate;

// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The model to policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
        Post::class => PostPolicy::class
    ];

 

then add to the controller 
 

 

    $this->authorize('update', $post);