Extending or customizing laravel core bindings
Do you wonder how laravel hands over the request to you when you type-hint the Request
in controller argument. It’s can do this because the request instance is bound in app container with key request
. In the same way there are other things like auth
, response
etc which are bound in the app container.
In this post we will look at how we can extend laravel core bindings and add custom method on core AuthManager
class.
Whenever you use auth()
helper function or Auth
facade. What laravel does is it pulls out AuthManager
from service container with key auth
and hands over to us.
Now, let’s extends the core AuthManager
and add a isAdmin
function to it which determines if the current user is admin or not.
If you remember macros from this post, you might be thinking why not add a marco to Auth
. Unfortunately we cannot do that because AuthManager
doesn’t use Macroable
trait. It has it’s own implementation of __call
magic method to call non existing methods on auth driver.
Before we start lets add isAdmin
function to User
modal which will tell us if that user is admin or not.
public function isAdmin() {
return $this->id == 1;
}
For example purpose we will make a user admin if his id is 1. In real, what you should do instead is check if user has a admin role or something like that.
Now, Let’s create a Auth
folder in app and then create AuthManager.php
file. Paste the below code in it.
First, we receive auth
and app
in our constructor arguments. Assign the auth
instance to member variable auth
and invoke the parent constructor passing app
.
And finally add our isAdmin
method which check if user is logged in and call isAdmin
on user.
Extending
Everything is setup, the only thing left to do is tell laravel to use our custom AuthManager
instead of core one. We will do that is register
method of AuthServiceProvider
public function register(){ $this->app->extend('auth', function($auth, $app) {
return new \App\Auth\AuthManager($auth, $app); });
}
Let’s test
We’ll test this in 3 cases.
- When user is not logged in.
- When admin user is logged in.
- When non-admin user is logged in.
I assume that you have database setup and seeded some data in users table
Here are our tests
Run tests
We run the tests
I hope you got to learn something new today. Feel free to reach out me for any questions.
Thank you.