My question is simple, yet I couldn't find any answer to this question.
I use Policies to authorize CRUD operations.
I use Gates to authorize other non-model related actions.
I perform these authorizations in the Controller files.
...
In the meanwhile, I validate form inputs inside the FormRequest files.
My question is. Why would anyone perform authorization in the FormRequest file? Isn't it better to have it all in the controllers?
BlogPostController code:
class BlogPostController extends Controller
{
public function __construct(){
$this->middleware('auth', ['except' => ['index', 'show']]);
}
public function index()
{
// Okay, I authorize by gate here
if (\Gate::denies('example-gate-authorization')){
return redirect()->route('index');
}
$posts = BlogPost::with('user')->latest()->paginate(5);
return view('posts.index', compact("posts"));
}
public function create()
{
// Okay, I authorize by policy here
$this->authorize("create", BlogPost::class);
$post = new BlogPost();
return view('posts.createOrEdit', compact('post'));
}
// etc...
}
BlogPostRequest code:
class BlogPostRequest extends FormRequest
{
public function authorize()
{
// BUT why would anyone authorize anything in here ???
return true;
}
public function rules()
{
// Yeah the rules are okay here ..
return [
'title' => 'required|max:255|unique:posts' . ($this->post ? (',title,' . $this->post->title . ',title') : ''),
'body' => 'required'
];
}
}
Is there any practical reason when a developer would choose FormRequest authorization over Controller/Policy,Gate authorization?
(Yes, I know one can use Gates in the FormRequest file too)