【发布时间】:2018-11-14 14:57:24
【问题描述】:
我有一个处理查询过滤器的控制器,现在过滤器的一部分需要用户登录才能应用过滤器。最好的方法是什么?感谢任何帮助!非常感谢!
API 路由: Route::get('toyslist','toyslistController@index');
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Toylist;
class ToyslistController extends Controller
{
public function index(Request $request)
{
$toyslist = (new Toylist)->newQuery();
if($request->has('type')){
$toy_typeArray = explode(',',$request->type);
$toyslist->whereIn('type',$toy_typeArray);
}
if($request->has('age')){
$toy_ageArray = explode(',',$request->type);
$toyslist->whereIn('age',$toy_ageArray);
}
if($request->has('brand')){
$toy_brandArray = explode(',',$request->type);
$toyslist->whereIn('brand',$toy_brandArray);
}
if($request->has('storage')){
if(Auth::check()){
$toy_storageArray = explode(',',$request->type);
$toyslist->whereIn('storage',$toy_storageArray);
}
}
return $toyslist->paginate(15);
}
}
【问题讨论】:
-
你目前的方法有什么问题?
-
使用 Route::get Auth::check() 或 Auth::id() 总是返回空,我不想在路由中使用中间件来阻止公开使用过滤器。有没有办法解决这个问题,还是我必须使用路由中间件复制相同的方法并将其留给非路由中间件?
-
我唯一要改变的是将身份验证检查放在上面的检查中,例如
if ($request->has('storage') && Auth::check()) {. -
Auth::check()不应返回false,除非用户未登录。您是在请求中使用web中间件还是 API 路由? -
只是检查一下,但我假设
$request->type并不是要在所有 if 语句中使用?