Search code examples
phplaravelmiddleware

How to prevent action from happening with middleware in Laravel


I have the following route:

Route::get('post/{postId}/deleteComment/{commentId}', [
    'uses' => 'CommentController@getDeleteComment',
    'as' => 'content.post.deleteComment'
])->middleware('checkDeleteComment');

and the following middleware:

namespace App\Http\Middleware;

use App\Comment;
use Closure;
use Auth;

class checkDeleteComment
{
    public function handle($request, Closure $next)
    {
       $id = $request->route()->parameter('commentId');

       $comment = Comment::where('id', $id)->first();

        if (! Auth::user()->id == $comment->user_id) {
            return redirect()->back();
        } else {
            return $next($request);
        }
    }
}

The middleware is in my App/Http/Kernel.php as followed:

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'checkAdmin' => \App\Http\Middleware\checkAdmin::class,
        'checkDeleteComment' => \App\Http\Middleware\checkDeleteComment::class,
    ];

Yet when I try to delete a comment that is not mine with the given link, I always succeed. Can someone help me?


Solution

  • instead of saying is not do is not equal

    if (Auth::user()->id != $comment->user_id) {