Search code examples
phplaravelroutesaclpolicies

Different Policies for "Resource" routes in Laravel


I have a system where Admin can manage doctors and doctor has ability to manage itself. For this, I am using Laravel Authorization using policies. I registered a policy for admins that it can access doctors like:

Route::resource('doctors', 'DoctorsController')->middleware('can:access-doctors, App\Doctor');

But what I need is a separate policy for just one route out of resource group i.e. doctors.edit so a doctor can edit own profile like: can:edit-doctor, $doctor something.

Is there a possibility to do this in a proper way or I have to make manual routes and assign policies rather than using resource routes???


Solution

  • If I'm not wrong, you'll need a different endpoint to specify specific middlewares for each route.

    You could do:

    Route::get('doctors/{doctor}/edit', 'DoctorsController@edit')
        ->middleware('can:edit-doctor', 'App\Doctor'));
    
    Route::put('doctors/{doctor}', 'DoctorsController@update')
        ->middleware('can:edit-doctor', 'App\Doctor'));
    
    Route::resource('doctors', 'DoctorsController')
        ->except(['edit', 'update'])
        ->middleware('can:access-doctors, App\Doctor'));