laravelpolicy

The policies in Laravel are not working for me, this is my code


I can't get the policies to work in my Laravel project, I installed a new project to test from scratch, I have this controller:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $this->authorize('viewAny', auth()->user());
        return response("Hello world");
    }
}

This policy:

<?php

namespace App\Policies;

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

class UserPolicy
{    
    public function viewAny(User $user): bool
    {
        return true;
    }
}

and this my model

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];
}

And I get error 403: THIS ACTION IS UNAUTHORIZED. I hope someone can help me with my problem. Thank you

I have also tried to modify the AuthServiceProvider file, but nothing has changed.


Solution

  • You are trying to verify that the user has permission to access the page. Make sure that whoever is trying to access the page is a user, so that the policy can authorize it or not.

    To test without a starter kit, create a user and log in with it.

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Support\Facades\Auth;
    
    class UserController extends Controller
    {
        public function index()
        {
            // create a new user
            $user = \App\Models\User::factory()->create();
    
            // login with the created user
            Auth::login($user);
            $this->authorize('viewAny', \App\Models\User::class);
            return response("Hello world");
        }
    }
    

    However, if you wish to grant access to guest users, you can utilize the ? symbol to make the User model optional:

    public function viewAny(?User $user)
    {
        return true;
    }