Middleware for post manipulation

1

I've created a middleware to check if the person who wants to manipulate a post owns it or is super admin . See:

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 section:

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

I had to insert a @ to suppress an error that occurs when the post is not being manipulated is not related to the session user. Is there a more appropriate way to do this same logic but without inserting another if ?

    
asked by anonymous 19.12.2016 / 15:19

1 answer

2

The variable $post needs to be checked if it is different from null , so try this setting:

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

or

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

Note: do not use @ to suppress a problem that can be solved     

19.12.2016 / 15:31