php - Can someone explain what this code does in laravel


I think i have a rough idea of what a guard does. for some reason there's not really much write-up about it online. I saw this line of code in someones middleware

public function __construct(Guard $auth)
    $this->auth = $auth;

and i don't understand what it does. i understand that there two types of inbuilt guards-web and api and web is the default guard. What does the "Guard" inside the construct do? and how does the $auth variable come into play?.

here's the pic of the full codeenter image description here




TheGuard class is used for authentication i.e. logging a user in, checking to see if there is an authenticated user, retrieving the authenticated user, logging them out etc.

I'd say the most common way to access this information (going off the docs and various tutorials) is by using either theAuth Facade or the auth() helper function. With either approach you will have access to the same methods e.g.

auth()->user() orAuth::user() will return the current authenticated user.
auth()->id() orAuth::id() will return the current authenticated user'sid.
auth()->check() orAuth::check() will tell you if the current user is logged in or not.

In either case (usingauth()-> orAuth::) you're going to accessing methods on theGuard class.

Laravel also has something called the Service Container which is a way for you to be able to have dependency injection. This is essentially where you can get an instance of a class automatically without having to do something likenew ClassName(). This might not seem like a big deal at first but if you have a class that needs to be passed different variable and classes to its constructor you can set this up in the container so you don't have to worry about it. Another benefit might be that you want to use the same instance of a class rather than creating a new one each time which is something that can be done with the container as well.

Now, some people prefer to use dependency injection instead of using Facades or helper functions (see here for more information). With the case in your example you're injecting theGuard class so that you can access it as a property on the class rather than using the Facade or helper function. There isn't more to it than that.

People are also looking for solutions to the problem: php - Javascript error receiving data from JSON echo


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.