0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

@iCode, I need you help. Look here : stackoverflow.com/questions/41030097/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.