Middleware for post handling

Asked

Viewed 31 times

1

I created a middleware to check if the person who wants to manipulate a post owns this one or if it’s the super admin. Behold:

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

    if ($user->id == 2 || @$post->user_id == $user->id) {
        return $next($request);
    }

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

But in this passage:

if ($user->id == 2 || @$post->user_id == $user->id) {

I had to enter a @ to suppress an error that occurs when the post not being manipulated is not related to the session user. Do you have a more appropriate way of making that same logic but without inserting one more if?

  • If you are using L5.3 you are searching for this: https://laravel.com/docs/5.3/authorization

1 answer

2


The variable $post needs to be checked if he’s different from null, then try this adjustment:

if ($user->id == 2 || ($post && $post->user_id == $user->id)) {

or

if ($user->id == 2 || (!is_null($post) && $post->user_id == $user->id)) {

Observing: don’t use @ to suppress a problem that has to be solved

Browser other questions tagged

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