Home > Software engineering >  How to access model instance in a Request class in Laravel 8?
How to access model instance in a Request class in Laravel 8?

Time:11-23

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?

CodePudding user response:

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);
}

CodePudding user response:

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
 */
  • Related