douxing5199 2014-10-15 15:08
浏览 38
已采纳

播种数据库 - [ErrorException]试图获取非对象的属性

I am using "zizaco/confide": "~4.0@dev" and "zizaco/entrust": "1.2.*@dev".

I have set everything up as described in the two tutorials(confide migrations). Furthermore, I have created the following models:

User:

    <?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 Eloquent implements UserInterface, RemindableInterface{
    use ConfideUser;
    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;
        }

    }

Role:

<?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;
    }
}

Permission:

<?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;
    }
}

Furthermore, I would like to seed my database in the beginning with values, therefore I created several seeders for user, role and permission. However, I get an error in my permission seeder:

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 );
    }

}

This is the error I get when running db:seed:

$ 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]

Any recommendations what I am doing wrong in my seeding?

I appreciate your answers!

  • 写回答

1条回答 默认 最新

  • douxuanou2787 2014-10-15 15:22
    关注

    I think the problem is with:

     $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;
    

    You want to get id but such records don't exists so you get the error. There are probably no records with admin, moderator or user name because looking at RolesTableSeeder you create roles this way:

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

    with names adminRole, userRole, modRole. So either change the names inside RolesTableSeeder or change them in PermissionsTableSeeder

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?