Search code examples
phplaravelif-statementmiddleware

My If statement is not working in Middleware


I am trying to make a middleware which can filter my http request by checking if the "$created_by" that I am passing through the request alreday exists in my "users" table
If it does I want to proceed with my "$next($request)"
And if it doesn't I wanna redirect it.

When the situation is this:-

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

It redirects to $next($request); which is correct
But when the "$request->created_by" is not present in DB it which makes $ip null
And it shows this error "Trying to get property 'uuid' of non-object"

Here's my Middleware:-

<?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);

        }
    }

Solution

  • you can use optional to prevent error if you object is null.

    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');
    
    }