devmyb
devmyb

Reputation: 375

How to get variable from middleware?

I've created my own middleware for API. Following is my code for getting valid User details based on the request params 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);

    }
}

But how can I access this $user variable within my Controller?

Upvotes: 0

Views: 108

Answers (1)

Amit Gupta
Amit Gupta

Reputation: 17708

You can use onceUsingId() to log a user into the application for a single request. No sessions or cookies will be utilized, which means this method may be helpful when building a stateless API:

So in your middleware you can use it as:

$user = User::where("access_token",$request->header('access-token'))->first();

if($user) {
   auth()->onceUsingId($user->id);
}

Then in your controller, you can use it as:

auth()->user()

Docs

Upvotes: 1

Related Questions