Laravel 中间件重定向如果 Table 为空

Laravel Middleware Redirect If Table is Empty

我正在尝试设置中间件以防止用户访问 URL,除非他们已将送货地址信息保存到我的数据库中。但是,它不起作用。

迁移:

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

中间件:

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

        return $next($request);
    }

addresses()关系方法returns一个QueryBuildertruethful。 我建议您使用 aggregate method count.

检查 地址 的计数
if ($request()->user()->addresses()->count() == 0) {
    return redirect('shipping');
}

如果你的中间件名称是 ex 的关系那么你可以给一个参数(关系名称)然后像这样在你的中间件中使用它 web.php

Route::get('shipings/{user}', 'GetShipingController@index')->middleware('relation:addresses');

和中间件

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

    return $next($request);
}