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?
AuthGuard is used to protect the routes from unauthorized access. So here we are creating an AuthGuard in angular that will protect our routes from unauthorized access. Example: We can create an AuthGuard by running simple command using CLI. ng g guard services/auth.
By default, web routes are configured to use the web guard and API routes are configured to use the api guard, and unless otherwise specified, Laravel will use the web guard by default.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With