Ad

Laravel Middleware Redirect If Table Is Empty

I am trying to set up middleware that prevents a user from visiting a URL unless they have saved their shipping address information to my database. However, it is not working.

Migration:

Schema::create('addresses', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->string('street');
            $table->string('city');
            $table->string('state');
            $table->string('zip');
            $table->string('country');
            $table->timestamps();
        });

Middleware:

public function handle($request, Closure $next)
    {
        if (!$request->user()->addresses('id')) {
            return redirect('shipping');
        }

        return $next($request);
    }
Ad

Answer

The addresses() relationship method returns a QueryBuilder which is truethful. I recommend that you check for the count of addresses instead by using the aggregate methodcount.

if ($request()->user()->addresses()->count() == 0) {
    return redirect('shipping');
}
Ad
source: stackoverflow.com
Ad