【问题标题】:Laravel filter & authenticationLaravel 过滤器和身份验证
【发布时间】: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 语句中使用?

标签: php laravel


【解决方案1】:

现在我做了以下工作:

添加 API 路由:

Route::middleware('auth:api')->get('protectedtoyslist','toyslistController@index');
Route::get('toyslist','toyslistController@index');

所以前端使用localhost/api/toyslist 来过滤未登录用户的无存储过滤器的产品。

对于已登录的用户,前端使用localhost/api/protectedtoyslist 过滤包含存储过滤器的产品。

如果有人对此有更好的方法,非常感谢。谢谢!

【讨论】:

    猜你喜欢
    • 2014-12-30
    • 2014-03-03
    • 1970-01-01
    • 2015-05-03
    • 2015-04-01
    • 2019-05-19
    • 1970-01-01
    • 2021-08-28
    • 2019-08-12
    相关资源
    最近更新 更多