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::get('/hapus/{id}','[email protected]')->middleware('cekstatus');


protected $middlewareGroups = [
    'web' => [
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        'cekstatus' => \App\Http\Middleware\CekStatus::class,

    'api' => [



1 Answers

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.