0

再会。我需要创建一个检查,授权用户的 id 与 user_id 数据库中的条目匹配。请帮帮我

中间件 CanEdit.php

    <?php

    namespace App\Http\Middleware;

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

    class CanEdit
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        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');
        }
    }
4

2 回答 2

0

你永远不会进入 if 条件,因为你在这里比较两个不同的类。如果您需要检查是否只有 id 匹配,您可以这样做:

$user = Auth::user()->id;
$editor = Pass::where('user_id', $user)->first();
if ($user == $editor->user_id) {
  return $next($request);
}

但在我看来,这个检查是没有必要的。假设user_idPass 表中的字段是唯一的,则不需要检查 id 是否匹配,只需要检查Pass表中是否存在记录:

$user = Auth::user()->id;
$editor = Pass::where('user_id', $user)->exists();
if ($editor) {
  return $next($request);
}

exists()方法仅根据记录是否存在于数据库中返回布尔值。

于 2021-04-02T07:53:32.150 回答
-1
if (Auth::guard($guard)->guest()) {
    if ($request->ajax() || $request->wantsJson()) {
        return response('Unauthorized.', 401);
    } else {
        return redirect()->guest('login');
    }
}
return $next($request);
于 2021-04-02T05:05:01.020 回答