我已经为API创建了自己的中间件。以下是根据请求参数access_token
namespace App\Http\Middleware;
use Closure;
use App\Exceptions\GeneralException;
use App\Models\Access\User\User;
class authNS
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
try {
$user = User::where("access_token",$request->header('access-token'))->with('details')->first();
} catch (Exception $e) {
return response()->json(['error'=>'Something is wrong']);
}
return $next($request);
}
}
但是如何在我的$user
Controller
变量
答案 0 :(得分:1)
您可以使用onceUsingId()
将用户登录到应用程序中以获取单个请求。不会使用会话或cookie,这意味着在构建无状态API时此方法可能会有所帮助:
因此,在您的middleware
中,您可以将其用作:
$user = User::where("access_token",$request->header('access-token'))->first();
if($user) {
auth()->onceUsingId($user->id);
}
然后在您的控制器中,您可以将其用作:
auth()->user()