I
I
Ilya Loopashko2021-04-02 09:00:01
Laravel
Ilya Loopashko, 2021-04-02 09:00:01

How to arrange validation in middleware?

I need to create a check, the id of the authorized user is the same as the user_id in the db table. My implementation doesn't work. Where did I go wrong?

<?php

namespace App\Http\Middleware;

use App\Models\Pass;
use Closure;
use Auth;
use Illuminate\Http\Request;

class CanEdit
{
    public function handle($request, Closure $next)
    {
        $user = Auth::user()->id;
        $editor = Pass::where('user_id', $user);
        if ($user == $editor) {
            return $next($request);
        }

        return redirect('home')->with('error','You have not access');
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2021-04-02
@delphinpro

$userId = Auth::user()->id; // Переменную плохо назвали. Это ID, а не пользователь
$editor = Pass::where('user_id', $userId)->first(); // А здесь редактор, не ID. Может быть NULL если не найдено.
// Нужно проверить, нашлась ли запись и совпали ли ID
//if ($editor && $userId == $editor->user_id) {        }

// Но исходя из условия запроса, если запись нашлась, то ID уже совпали
// Значит достаточно такой проверки:
if ($editor) {        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question