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

654 Views Asked by At

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?

2

There are 2 best solutions below

0
Rory On BEST ANSWER

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);
}
0
mrhn On

Alternative solution is that you can directly access your Models that are used with Model Binding.

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

For ease of use you can typehint it in the comments.

/**
 * @property \App\Models\Post $post
 */