Getting user id from Posts table

Asked by At

I have a route for destroying a Post, how can I make so that the one who can access the route is only the Post creator? For example, I have a Post with id number 3 and the user id is 5, so the only one who can delete number 3 is only user id 5. I've tried messing with middleware but not lucky enough to get it to work.

CekStatus.php (Middleware)

class CekStatus
{
    public function handle($request, Closure $next)
    {
        $userId = $request->id;
        $user = Post::where('id', $userId)->select('user_id')->pluck('user_id')->first();

        if ($user === Auth::id()) {
            return $next($request);
        }

        return redirect('/'); //redirect anyware.
    }
}

Route

Route::get('/hapus/{id}','[email protected]')->middleware('cekstatus');

Kernel.php

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cekstatus' => \App\Http\Middleware\CekStatus::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

Output:

ERR_TOO_MANY_REDIRECTS

1 Answers

1
nakov On

You should be using Policy here, the middleware is not used for authorization purposes. More on this in the docs here.

The docs use your example as well, instead of update you can create a delete function and then to use it in your controller you can add this:

if (auth()->user()->can('delete', $post)) {
    // delete it code here.
}