tighten / parental

Use single table inheritance in your Laravel app
MIT License
1.36k stars 98 forks source link

Call functions from child classes working with authenticated users #38

Closed Kovbo closed 5 years ago

Kovbo commented 5 years ago

This package works grate in tearms of incapsulation, I moved all logic into child classes exteding User model. However, it not possible anymore to work with authenticated users. I cannot call Auth::user()->profile() anymore, because this relation was extracted into subclass. It would be great to implement something like Auth::admin(), Auth::manager() in this package to work with authenticated users. Maybe It wold be nice to add some tutorial to readme explaining how to do it.

calebporzio commented 5 years ago

Ok, I created a test to reproduce this issue, and by the end of it, I believe it's not even an issue - but I could be wrong.

Did you add a "type" column to the User model and add the "HasChildren" trait to the User model?

If you haven't done those, do them and then let me know if the problem still persists. Here is my ridiculously hacky test for what it's worth:

    /** @test */
    function auth_user_returns_child_models()
    {
        app('auth')->extend('custom', function ($app, $name, array $config) {
            return new class ('session', auth()->createUserProvider($config['provider']), app('session.store')) extends SessionGuard
            {
                public function forceSetUser($user)
                {
                    $this->user = $user;
                }

                public function updateSession($id)
                {
                    return parent::updateSession($id);
                }
            };
        });

        app('config')->set('auth.guards.web.driver', 'custom');

        $admin = Admin::create([
            'name' => 'Caleb',
            'email' => 'something@something.com',
            'password' => 'secret',
        ]);

        $this->actingAs(Admin::first());

        app('auth')->updateSession($admin->id);
        app('auth')->forceSetUser(null);

        $this->assertInstanceOf(Admin::class, auth()->user());
    }
Kovbo commented 5 years ago

Wow, it really worked! I forgot to override both childColumn and childTypes in the User model, sorry about that. Now authenticated user returns child model. +1 star from me!

calebporzio commented 5 years ago

Saweeet! Thanks!