Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Custom function to Auth Class Laravel (Extends Guard Class)

I had modified a vendor file of Laravel placed at

/vendor/laravel/framework/src/Illuminate/Auth/Guard.php

but it will be overwritten upon updating Laravel.

I'm looking for a way to put the code somewhere in my /app to prevent the overwrite.

The function modified is

public function UpdateSession() {
    $this->session->set('type', $type); //==> Set Client Type
}

Also there's a new function on the file:

public function type() {
    return $this->session->get('type'); //==> Get Client Type
}

Codes above are called in many places in my application.

Any idea?

like image 732
Abbas Moazzami Avatar asked Oct 27 '15 12:10

Abbas Moazzami


1 Answers

Steps:
1- create myGuard.php

class myGuard extends Guard
{
    public function login(Authenticatable $user, $remember = false)
    {
        $this->updateSession($user->getAuthIdentifier(), $user->type);
        if ($remember) {
            $this->createRememberTokenIfDoesntExist($user);
            $this->queueRecallerCookie($user);
        }
        $this->fireLoginEvent($user, $remember);
        $this->setUser($user);
    }

    protected function updateSession($id, $type = null)
    {
        $this->session->set($this->getName(), $id);
        $this->session->set('type', $type);
        $this->session->migrate(true);
    }

    public function type()
    {
        return $this->session->get('type');
    }
}

2- in AppServiceProvider or new service provider or routes.php:

public function boot()
{
    Auth::extend(
        'customAuth',
        function ($app) {
            $model = $app['config']['auth.model'];
            $provider = new EloquentUserProvider($app['hash'],    $model);
            return new myGuard($provider, App::make('session.store'));
        }
    );
}

3- in config/auth.php

'driver' => 'customAuth',

4- now you can use this

Auth::type();
like image 52
Abbas Moazzami Avatar answered Nov 11 '22 01:11

Abbas Moazzami