laravel auth

two ways to authentication, based on session(cookie) or based on api(token),so we have two guards (web & api in config/auth.php).

guards have a driver and a provider,actually it’s just like controller and model.
driver: the logic u handle authentication
model: where u store your user data

#how it works
At first ,we need an entrance, we need to define some route.that’s why laravel map the route in provider/RouteServiceProvider

in RouteServiceProvider we have added a list of middlewares and  our custom route.
(Auth::routes() in web guard,
(in api guard, we need to add auth:api in middleware if u need authentication. like this :   Route::middleware(‘auth:api’)->group(…))

when u use Auth->attempt(), Auth->user() in your program, it’s actually interact from SessionGuard or TokenGuard.
(Auth alias AuthManager initialize a guard in the construction,and transfer the request to the guard)


pipeline in laravel


The concept is easy to understand,but the code is so confused. Every pipe will be run in order . Also they will get the data given by the previous pipe.

let’s see how Laravel get the job done .

Before dispatching  the request to router , Laravel will go through all the middleware first. The request object will be passed through all the middleware. middleware array is in the App\Http\Kernel

reference: array_reduce
array_reduce(pipes,callablecallable,initial)this->carry() will return a closure . two parameters (stack,pipe)  will be provided into this closure function . stack is the return value of the previous pipe.item is the current pipe. And initial will be the firststack, it’s a closure function too.


The following is how the pipe iterations work.
let’s say  pipe = [middleware1, middleware2] array_reverse will reverse thepipe array,so pipe = [middleware2,middleware1] ====================first iteration===================stack = dispatchToRouter
pipe = middleware2 so the return value = return function (passable) use (dispatchToRouter ,middleware2) { //….}
Let’s look into detail. u can see the passable andstack will pass into the middleware  as parameters.
it’s time to find out how a middleware looks like.

it will run the next function at the end of the handle function, and thenext is equal to it means it will call thestack at the end.
so the execute order looks like this :
dispatchToRouter  <- -call–  middleware2
=================second iteration=====================
stack = a closure return by first iterationpipe = middleware1
the same as first iteration, the return value will be a closure.
and the execute order will be :
dispatchToRouter <–call–middleware2 <–call– middleware1
u may be confuse ,they are all closure. when will all these closure get called?
look carefully into the then() function.
the last iteration will return a closure. and the then() function  invoke the closure and pass the request object as a parameter.

that’s it!