Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way in using Laravel 4 User model relations with Sentry 2 package

I'm trying to find out how to return the relations I set up for my User model when using Sentry 2.

Normally, I have a user retrieved like this:

$user = User::find(1);

// get some relation
return $user->profile->profile_name;

However, now when I have Sentry 2 implemented I can retrieve the logged in user like this:

$user = Sentry::getUser();

This way I can easily access the users table in my DB, but how do I go about fetching the relations and methods I have set up in my User.php model?

This seems way to clumpsy, and not Laravel-ish:

User::find(Sentry::getUser()->id)->profile->wizard_completed;

It seems somewhat... backwards.

Can you guys help me out? =)

like image 378
Marty Avatar asked Nov 30 '22 11:11

Marty


1 Answers

Extend Sentry creating your own User model with your relations on it:

<?php

use Cartalyst\Sentry\Users\Eloquent\User as SentryModel;

class User extends SentryModel {

    public function profile()
    {
        return hasOne(...);
    }

}

Publish sentry's config:

php artisan config:publish cartalyst/sentry

And tell Sentry to use your model, which now extending Sentry's has all of its functionalities plus yours:

'model' => 'User',

Then you'll be able to:

echo Sentry::getUser()->profile->wizard_completed;
like image 184
Antonio Carlos Ribeiro Avatar answered Dec 04 '22 02:12

Antonio Carlos Ribeiro