Search code examples
phpmysqllaravelpolicies

Laravel policies always return false


I have created policy, and add method view:

public function view(User $user, Contact $contact)
{
    return $user->id === $contact->manager;
} 

Then I have registered it:

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    Contact::class => ContactPolicy::class,
]; 

And then I have tried to use it with controller helper:

public function view($id)
{
    $contact = Contact::find($id);
    $user = Auth::user();

    $this->authorize('view', $contact);

    return view('contact.edit')->with('contact', $contact);
}

And middleware:

Route::get('/contact/edit/{id}', 'EditContactController@view')->middleware('can:view,contact');

But I always get 403 error. contact->manager and user->id are the same. Also, Contact table scheme:

CREATE TABLE `contacts` (
  `id` int(11) NOT NULL,
  `first_name` varchar(25) NOT NULL,
  `last_name` varchar(25) NOT NULL,
  `email` varchar(35) NOT NULL,
  `home_phone` int(10) DEFAULT NULL,
  `work_phone` int(10) DEFAULT NULL,
  `cell_phone` int(10) DEFAULT NULL,
  `best_phone` enum('home_phone','work_phone','cell_phone') NOT NULL,
  `address_1` varchar(100) DEFAULT NULL,
  `address_2` varchar(100) DEFAULT NULL,
  `city` varchar(35) DEFAULT NULL,
  `state` varchar(35) DEFAULT NULL,
  `zip` int(6) DEFAULT NULL,
  `country` varchar(35) DEFAULT NULL,
  `birth_date` date DEFAULT NULL,
  `manager` int(11) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Solution

  • I`ve just replaced

    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        Contact::class => ContactPolicy::class,
    ]; 
    

    with

    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        'App\Contact' => 'App\Policies\ContactPolicy',
    ];
    

    and now it works with $this->authorize('view', $contact);, but middleware still return 403