【问题标题】:Laravel 4.2 - Using entrust and confideLaravel 4.2 - 使用委托和信任
【发布时间】:2014-10-15 13:56:29
【问题描述】:

我正在使用"zizaco/confide": "~4.0@dev""zizaco/entrust": "1.2.*@dev"

我已经按照两个教程(confide migrations)中的描述设置了所有内容。此外,我还创建了以下模型:

用户:

<?php

use Zizaco\Confide\ConfideUser;
use Zizaco\Confide\Confide;
use Zizaco\Confide\ConfideEloquentRepository;
use Zizaco\Entrust\HasRole;
use Carbon\Carbon;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends ConfideUser implements UserInterface, RemindableInterface{
    use HasRole;

    /**
     * Get user by username
     * @param $username
     * @return mixed
     */
    public function getUserByUsername( $username )
    {
        return $this->where('username', '=', $username)->first();
    }

    public function joined()
    {
        return String::date(Carbon::createFromFormat('Y-n-j G:i:s', $this->created_at));
    }

    public function saveRoles($inputRoles)
    {
        if(! empty($inputRoles)) {
            $this->roles()->sync($inputRoles);
        } else {
            $this->roles()->detach();
        }
    }

    public function currentRoleIds()
    {
        $roles = $this->roles;
        $roleIds = false;
        if( !empty( $roles ) ) {
            $roleIds = array();
            foreach( $roles as &$role )
            {
                $roleIds[] = $role->id;
            }
        }
        return $roleIds;
    }

    public static function checkAuthAndRedirect($redirect, $ifValid=false)
    {
        // Get the user information
        $user = Auth::user();
        $redirectTo = false;

        if(empty($user->id) && ! $ifValid) // Not logged in redirect, set session.
        {
            Session::put('loginRedirect', $redirect);
            $redirectTo = Redirect::to('user/login')
                ->with( 'notice', Lang::get('user/user.login_first') );
        }
        elseif(!empty($user->id) && $ifValid) // Valid user, we want to redirect.
        {
            $redirectTo = Redirect::to($redirect);
        }

        return array($user, $redirectTo);
    }

    public function currentUser()
    {
        return (new Confide(new ConfideEloquentRepository()))->user();
    }

    public function getReminderEmail()
    {
        return $this->email;
    }

}

角色:

<?php

use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole {

    public function validateRoles( array $roles )
    {
        $user = Confide::user();
        $roleValidation = new stdClass();
        foreach( $roles as $role )
        {
            // Make sure theres a valid user, then check role.
            $roleValidation->$role = ( empty($user) ? false : $user->hasRole($role) );
        }
        return $roleValidation;
    }
}

权限:

<?php

use Zizaco\Entrust\EntrustPermission;

class Permission extends EntrustPermission
{
    public function preparePermissionsForDisplay($permissions)
    {
        // Get all the available permissions
        $availablePermissions = $this->all()->toArray();

        foreach($permissions as &$permission) {
            array_walk($availablePermissions, function(&$value) use(&$permission){
                if($permission->name == $value['name']) {
                    $value['checked'] = true;
                }
            });
        }
        return $availablePermissions;
    }

    /**
     * Convert from input array to savable array.
     * @param $permissions
     * @return array
     */
    public function preparePermissionsForSave( $permissions )
    {
        $availablePermissions = $this->all()->toArray();
        $preparedPermissions = array();
        foreach( $permissions as $permission => $value )
        {
            // If checkbox is selected
            if( $value == '1' )
            {
                // If permission exists
                array_walk($availablePermissions, function(&$value) use($permission, &$preparedPermissions){
                    if($permission == (int)$value['id']) {
                        $preparedPermissions[] = $permission;
                    }
                });
            }
        }
        return $preparedPermissions;
    }
}

此外,我想在一开始就为我的数据库播种值,因此我创建了以下播种器:

UserTableSeeder:

<?php

class UsersTableSeeder extends Seeder {

    public function run()
    {
        DB::table('users')->delete();


        $users = array(
            array(
                'username'   => 'admin',
                'email'      => 'admin@example.org',
                'password'   => Hash::make('admin'),
                'confirmed'  => 1,
                'confirmation_code' => md5(microtime().Config::get('app.key')),
                'created_at' => new DateTime,
                'updated_at' => new DateTime,
            ),
            array(
                'username'   => 'moderator',
                'email'      => 'moderator@example.org',
                'password'   => Hash::make('moderator'),
                'confirmed'  => 1,
                'confirmation_code' => md5(microtime().Config::get('app.key')),
                'created_at' => new DateTime,
                'updated_at' => new DateTime,
            ),
            array(
                'username'   => 'user',
                'email'      => 'user@example.org',
                'password'   => Hash::make('user'),
                'confirmed'  => 1,
                'confirmation_code' => md5(microtime().Config::get('app.key')),
                'created_at' => new DateTime,
                'updated_at' => new DateTime,
            )
        );

        DB::table('users')->insert( $users );
    }

}

RolesTableSeeder:

<?php

class RolesTableSeeder extends Seeder {

    public function run()
    {
        DB::table('roles')->delete();

        $adminRole = new Role;
        $adminRole->name = 'adminRole';
        $adminRole->save();

        $standRole = new Role;
        $standRole->name = 'userRole';
        $standRole->save();

        $modRole = new Role;
        $modRole->name = 'modRole';
        $modRole->save();

        $user = User::where('username','=','admin')->first();
        $user->attachRole( $adminRole );

        $user = User::where('username','=','user')->first();
        $user->attachRole( $standRole );

        $user = User::where('username','=','moderator')->first();
        $user->attachRole( $modRole );

    }
}

PermissionsTableSeeder:

<?php

class PermissionsTableSeeder extends Seeder {

    public function run()
    {
        DB::table('permissions')->delete();

        $permissions = array(
            array( // 1
                'name'         => 'manage_users',
                'display_name' => 'manage users'
            ),
            array( // 2
                'name'         => 'manage_roles',
                'display_name' => 'manage roles'
            ),
            array( // 3
                'name'         => 'standart_user_role',
                'display_name' => 'standart_user_role'
            ),
        );

        DB::table('permissions')->insert( $permissions );

        DB::table('permission_role')->delete();

        $role_id_admin = Role::where('name', '=', 'admin')->first()->id;
        $role_id_mod   = Role::where('name', '=', 'moderator')->first()->id;
        $role_id_stand = Role::where('name', '=', 'user')->first()->id;

        $permission_base = (int)DB::table('permissions')->first()->id - 1;

        $permissions = array(
            array(
                'role_id'       => $role_id_admin,
                'permission_id' => $permission_base + 1
            ),
            array(
                'role_id'       => $role_id_admin,
                'permission_id' => $permission_base + 2
            ),
            array(
                'role_id'       => $role_id_mod,
                'permission_id' => $permission_base + 1
            ),
            array(
                'role_id'       => $role_id_mod,
                'permission_id' => $permission_base + 3
            ),
            array(
                'role_id'       => $role_id_stand,
                'permission_id' => $permission_base + 3
            ),
        );

        DB::table('permission_role')->insert( $permissions );
    }

}

但是,当运行db:seed:

$ php artisan db:seed
**************************************
*     Application In Production!     *
**************************************

Do you really wish to run this command? Y
Seeded: UsersTableSeeder
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","me
ssage":"Class User cannot extend from trait Zizaco\\Confide\\ConfideUser","file"
:"C:\\xampp\\htdocs\\laravel_project\\laravel-application\\app\\models\\User.php","line
":11}}

任何建议我在播种时做错了什么?

感谢您的回答!

更新

更改UserModel 后出现以下异常:

$ php artisan db:seed
**************************************
*     Application In Production!     *
**************************************

Do you really wish to run this command? Y
Seeded: UsersTableSeeder
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","me
ssage":"Call to undefined method User::where()","file":"C:\\xampp\\htdocs\\larav
el_project\\laravel-application\\app\\database\\seeds\\RolesTableSeeder.php","line":21}
}

更新 2

将用户模型更改为(如@MarcinNabiałek 建议的那样):

class User extends Eloquent implements UserInterface, RemindableInterface{
    use ConfideUser;
    use HasRole;

我收到以下错误:

$ php artisan db:seed
**************************************
*     Application In Production!     *
**************************************

Do you really wish to run this command? Y
Seeded: UsersTableSeeder
Seeded: RolesTableSeeder



  [ErrorException]
  Trying to get property of non-object



db:seed [--class[="..."]] [--database[="..."]] [--force]

【问题讨论】:

    标签: php laravel laravel-4 seeding


    【解决方案1】:

    你在这里有明确的信息 - 你不能从 Trait 扩展(我认为消息很清楚:Class User cannot extend from trait Zizaco\Confide\ConfideUser)。

    代替:

    class User extends ConfideUser implements UserInterface, RemindableInterface{
        use HasRole;
    

    你应该使用:

    class User implements UserInterface, RemindableInterface{
        use ConfideUser;
        use HasRole;
    

    编辑

    User 类显然应该扩展 Eloquent(这是默认设置)所以它应该是:

    class User extends Eloquent implements UserInterface, RemindableInterface{
        use ConfideUser;
        use HasRole;
    

    【讨论】:

    • 非常感谢您的回答!我按照您的建议更改了 UserModel。但是,现在我的 RoleSeeder 出现错误。非常感谢您对此的回复!
    • 谢谢,我进行了更改以扩展 Eloquent。但是,现在我收到了用户和角色表播种的错误,但是权限表失败了:` [ErrorException] Trying to get property of non-object` 针对该错误有什么建议吗?
    • @mrquad 你需要问另一个问题,显示确切的错误
    • 我添加了一个更新,因为我认为以下错误对于另一个问题来说太小了。非常感谢您对此的看法!
    • 这可能是因为PermissionsTableSeederRole 但你应该自己检查并提出新问题,如果这个播种机引起问题
    猜你喜欢
    • 2010-11-10
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多