Laravel What is a guard?

user1157885 picture user1157885 · Jan 20, 2016 · Viewed 51k times · Source

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?

Answer

Jamkoko picture Jamkoko · Aug 15, 2016

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.