Search code examples
laravelauthorizationlaravel-8laravel-authorizationlaravel-request

How to access model instance in a Request class in Laravel 8?


In my Laravel project I want to authorize user via a Request like this:

<?php

namespace Domain\Contents\Http\Requests\Blog;

use Domain\Contents\Models\Blog\Post;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Gate;

class ReadPostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        if (request('id') === null) {
            abort(403);
        }

        $post = Post::whereId(request('id'))->first();

        return Gate::allows('view-post', $this->user(), $post);
    }

    // ...
}

But I think here this part of my code is little bit messy:

if (request('id') === null) {
    abort(403);
}

$post = Post::whereId(request('id'))->first();

Is there any simpler solution for accessing current Post model in the Request class?


Solution

  • The documentation for FormRequests suggests that the authorize() method supports type hinting.

    If you are using route model binding you could therefore just type hint the post:

    public function authorize(Post $post)
    {
        return Gate::allows('view-post', $this->user(), $post);
    }