我的 If 语句在中间件中不起作用

My If statement is not working in Middleware

我正在尝试制作一个中间件,它可以通过检查我正在传递请求的 "$created_by" 是否存在来过滤我的 http 请求我的 "users" table
如果是这样,我想继续 "$next($request)"
如果没有,我想重定向它。

当情况是这样的:-

if ($ip->uuid == $request->created_by)

它重定向到 $next($request); 这是正确的
但是当 "$request->created_by" 不存在于 DB 中时,它使 $ip 为空
它显示此错误 "Trying to get property 'uuid' of non-object"

这是我的中间件:-

<?php

namespace App\Http\Middleware;

use Closure;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;


class Posts
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)

     {
      $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();
        // dd($ip);
       if ($ip->uuid == $request->created_by) {
        if ($ip == null) {
             return redirect('https://www.google.com');
        }


       }

        return $next($request);

        }
    }

编辑:

您已经在数据库中进行了比较,将 handle() 更新为:

    public function handle($request, Closure $next)
    {
       $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();

       if (is_object($ip) {

         return $next($request);

       }

       return redirect('https://www.google.com');
    }

在尝试访问 属性 uuid 之前,您必须确保 $ip 不为空。

public function handle($request, Closure $next) {
    $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();
    if(is_null($ip) || $ip->uuid !== $request->created_by) {
        return redirect('https://www.google.com');
    }

    return $next($request);
}

如果您的对象为 null,您可以使用 optional 来防止错误。

public function handle($request, Closure $next) {
    $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();
    if(optional($ip)->uuid == $request->created_by) {
        return $next($request);
    }

    return redirect('https://www.google.com');

}