Laravel What is a guard?
I was looking through the built in auth controllers and I noticed they use something called "Guards". Up until now whenever I made my own logins/register forms I never touched these and would usually just do things like:
Auth::attempt()
without any type of guard. I've tried looking up what exactly it is but I couldn't really find any information on it, could someone explain to me what the purpose of the guards are?
Solution 1:
They're the definition of how the system should store and retrieve information about your users.
You can find the configuration in your config/auth.php
file. A web guard is the traditional cookie store - so that web guard instructs Laravel to store and retrieve session information the classic way. The API guard, on the other hand, uses tokens. So you would use the API guard if you want to authenticate users and requests using an API token in the header (bearer) or query parameter.
You can also create your own guard if you wish, and there's also this good introductory blog post on the topic by Matt Stauffer.
Solution 2:
Since I had the same question and the other answers did not provide me the information I was looking for (they explain perfectly what a guard does, but not why you should ever worry about calling its methods), I will provide another answer.
I was also unsure about the difference between methods provided by the auth()
helper and methods provided by the guard itself auth()->guard()
, as they seemed to do the same.
A quick dd(auth())
reveals that it returns an instance of AuthManager
. So we can look up that class in the source code: On the bottom of AuthManager.php there is a __call()
magic method which forwards all undefined calls to its own guard()
method.
public function __call($method, $parameters)
{
return $this->guard()->{$method}(...$parameters);
}
This clearly shows us that the methods of auth()
and auth()->guard()
not only seem to do the same, but are exactly the same. So as long as the default guard should be used, an additional ->guard()
can be omitted with peace of mind.
Solution 3:
A guard is a way of supplying the logic that is used to identify authenticated users. Laravel provides different guards like sessions and tokens. The session guard maintains the state of the user in each request by cookies, and on the other hand, the token guard authenticates the user by checking a valid token in every request.
Solution 4:
Guard role is to authenticate routes
- Web guard will authenticate web routes
- Api guard will authenticate api routes.
- For other user types e.g Admin guard will authenticate admin routes and so on.