Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 334
user1157885 Avatar asked Jan 20 '16 09:01

user1157885


People also ask

What is an authentication guard?

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.

What is the default guard in Laravel?

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.


2 Answers

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.

like image 111
Sam Avatar answered Sep 23 '22 12:09

Sam


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.

like image 40
debite Avatar answered Sep 21 '22 12:09

debite