Optimizing default middleware behavior

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

Would it be possible to pass this value to the controller as a middleware return?

    
asked by anonymous 19.12.2016 / 18:29

1 answer

1

Answer to question

Not possible.

You must return an instance of Illuminate\Http\Request because other middlewares expect an instance of this class to continue their work. If you spend anything else, they will be confused and will not know what to do. Thus generating an error.

Recommendation

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

    
01.03.2017 / 23:21