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 ?