RomainB's avatar

RomainB wrote a reply+100 XP

2mos ago

This is the way for Laravel version <= 10.

After that, you need to make your controller extends from Illuminate\Routing\Controller and use the trait Illuminate\Foundation\Auth\Access\AuthorizesRequests:

use App\Models\Client;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Routing\Controller;

abstract class APIController extends Controller
{
    use AuthorizesRequests;

    public function __construct()
    {
        $this->authorizeResource(Client::class);
    }
RomainB's avatar

RomainB liked a comment+100 XP

2mos ago

I'm using Laravel 10 and I've been able to apply my policy to a Route::resource by adding a single line of code to the corresponding controller constructor, as described here in the Laravel Documentation.

In routes/web.php:

...
Route::middleware([
    'auth:sanctum',
    config('jetstream.auth_session'),
    'verified',
])->group(function () {

    Route::resource('clients', ClientController::class)
        ->only(['index', 'store', 'edit', 'update', 'destroy']); 
});
...

In app/Http/Controllers/ClientController.php:

<?php

namespace App\Http\Controllers;

use App\Models\Client;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class ClientController extends Controller
{
    /**
     * Create the controller instance.
     */
    public function __construct()
    {
        $this->authorizeResource(Client::class, 'client');
    }    

    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        return view('clients.index', [
            'clients' => Client::all(),
        ]);
    }
...
    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Client $client): View
    {
        return view('clients.edit', [
            'client' => $client,
        ]);
    }
...

In app/Policies/ClientPolicy.php:

<?php

namespace App\Policies;

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

class ClientPolicy
{

    /**
     * Determine whether the user can view any models.
     */
    public function viewAny(User $user): bool
    {
        return $user->hasAbilityTo('view clients');
    }

    /**
     * Determine whether the user can view the model.
     */
    public function view(User $user, Client $client): bool
    {
        return $user->hasAbilityTo('view clients');
    }
...
    /**
     * Determine whether the user can update the model.
     */
    public function update(User $user, Client $client): bool
    {
        return $user->hasAbilityTo('update clients');
    }

By the way, I've not needed to add anything to app\Providers\AuthServiceProvider.php.

I hope that's of some use to people arriving at this post.