Looking at the laravel docs for controllers, they have an example where they authorize actions via a policy inside a Controller class:
$this->authorize('action',$model);
Yet checking the laravel doc api, I can see that the base controller class has no authorize method. How does this work?
If I take a look at a standard controller that is scaffolded by Laravel, you'll see that it extends a "base" controller in your app/Http/Controllers
folder;
use App\Http\Controllers\Controller;
class YourController extends Controller
{
//...
If you go and take a look at this "base" Controller
class:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
You can see that this is using the AuthorizesRequests
trait.
If you go and take a look in the AuthorizesRequests
trait you'll see these authorisation methods.
One of which is:
public function authorize($ability, $arguments = [])
{
[$ability, $arguments] = $this->parseAbilityAndArguments($ability, $arguments);
return app(Gate::class)->authorize($ability, $arguments);
}
This is how the authorize
method works and is provided to your controllers.