0

我有用户表。这些用户表具有 company_id 属性。

我有一些带有 id 的通用页面。

https://www.test.com/customer_question/p/4701/c/40960

仅当登录用户具有特定的 company_id 时才需要访问此 url。否则其他一些人可以通过增加 IDS 来访问链接

因此,在每个控制器(索引、存储、更新等)中,我必须检查类似这样的内容

$company_id = Auth::user()->company_id;
$verify_seller = DB::table('sellers')
    ->select('*')
    ->where('company_id', '=', $company_id)
    ->get();

if ($verify_seller->isEmpty())
    return "This product neither belongs to your seller account nor another seller's product";

我想我可以通过将上面的代码放到每个客户的 _construct 函数中来处理这个问题。

用 Laravel 处理这种情况的最佳方法是什么?

Laravel 5.6 版

4

1 回答 1

2

两种方式。

  1. 中间件

    class CheckSeller
    {
         public function handle($request, Closure $next, $guard = null)
        {
              $company_id = Auth::user()->company_id;
              $verify_seller = DB::table('sellers')
              ->select('*')
              ->where('company_id', '=', $company_id)
              ->get();
              if ($verify_seller->isEmpty()) {
                    return redirect()->route('main')->withError('Not Allowed')
              }
    
              return $next($request);
        }
    }
    

    在内核.php

    protected $routeMiddleware = [
         ....
         'check_seller' => \Illuminate\Auth\Middleware\CheckSeller::class,
    ]
    

    在路线中

    Route::middleware(['check_seller'])->group(function () {
         //any controller that need to use the check_seller middleware
    });
    

    或者如果你需要在每个控制器中做,你可以这样做..

    class Example extends Controller {
          public function __construct()
          {
               $this->middleware('check_seller');
          }
    }
    



2.基础控制器

    class BaseController extends Controller {
          public function __construct()
          {
               $company_id = Auth::user()->company_id;
               $verify_seller = DB::table('sellers')
               ->select('*')
               ->where('company_id', '=', $company_id)
               ->get();
               if ($verify_seller->isEmpty()) {
                    return redirect()->route('main')->withError('Not Allowed')
               }
          }
    }

在子控制器中

    class SellerController extends BaseController {
          public function __construct()
          {
               parent::__construct();
          }
    }
于 2018-04-08T13:17:30.937 回答