Optimizing Middleware Standard Behavior

Asked

Viewed 81 times

2

I have the following middleware:

class OwnerOrAdmin
{
    public function handle($request, Closure $next)
    {
        $user = \Auth::user();
        $postId = $request->route('post');
        $post = $user->posts->find($postId);

        if ($user->id == 1 || (!is_null($post) && $post->user_id == $user->id)) {
            return $next($request);
        }

        return redirect()->route('post.index')
                ->with(['status' => 'danger', 'mensagem' => 'Este post não te pertence!']);
    }
}

Basically this check if the user who will edit a post is Admin (id=1) or if this is the owner of the post.

But in my controller I have to repeat practically the same query to the bank:

public function edit($id)
{
    $post = Post::find($id);

    return view('painel.post.cad-edit', compact('post'));
}

It would be possible to pass this value to the controller as return from middleware?

  • The best way to do this is by using Authorization instead of middleware. https://laravel.com/docs/5.3/authorization

  • Later I’ll give you an answer.

  • Had done via Authorization, however, I did not like the result very much. Via middleware I can validate and already indicate the return message applied only the routes (Resource) store, update and Destroy. When I did via Authorization I had to "modify" the controller, something I would like to avoid if possible

  • Tried to do via Form Request?

  • In this case, I wouldn’t answer. For example, on Edit and Destroy I need to pass only the registry id, so it wouldn’t make much sense to inject a custom Request.

  • Seria possível passar este valor para o controller como retorno do middleware? I saw that question and I read it, I reread it, but seriously nay It’s like, anything made for it can get weird (gambiarra), up to your middleware should return an error not a redirect (should not be a rule), maybe (I repeat maybe) make a cache to optimize bank research, but I have never tested Eloquent. If you’re worried maybe about the repetition of SQL (select * from posts where id = 1)in this case there are not so many problems and the repetition of the code are at different times

Show 1 more comment

1 answer

1

Answer to question

Is not possible.

You must return an instance of Illuminate\Http\Request because other middleware are waiting for an instance of this class to continue their work. If you pass anything else, they will get confused and will not know what to do. Thus generating a mistake.

Recommending

Since this duplication is a problem in your case, I recommend you move the middleware code to your controller and give a second chance to authorizarion in Laravel. Because for what you’re trying to do, this is the functionality recommended by the framework.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.