【问题标题】:Call to a member function toArray() on integer在整数上调用成员函数 toArray()
【发布时间】:2020-03-16 14:44:28
【问题描述】:

User.php

public function role()
{

    return $this->belongsToMany('App\Models\Role','user_role','user_id','role_id');

}

//проверка принадлежит ли пользователь к какой либо роли
public function  isEmloyee(){
    $role=$this->role->toArray();
    return !empty($role);
}
//проверка имеетли пользователь определению роли
public function hasRole($check){

    return in_array($check,array_pluck($this->role->toArray(),'name'));
}
//получение идентификатора роли
private function getIdinArray($array,$term){
    foreach ($array as $key => $value){
        if ($value == $term){
            return $key +1;
        }
        return false;
    }
}
//добавление роли пользователя
public function makeEmployee($title){
    $assiqned_role = array();
    $role = array_pluck(Role::all()->toArray(),'name');
    switch ($title){
        case 'admin':
            $assiqned_role[] = $this->getIdinArray($role,'admin');
        case 'client':
            $assiqned_role[] = $this->getIdinArray($role,'client');
            break;
        default:
            $assiqned_roles[] = false;
    }
    $this->role()->attach($assiqned_role);
}

Role.php

class Role extends Model
{

   public function users()
   {

       return $this->belongsToMany('App\Models\User','user_role','role_id');
   }

}

OwnerMiddleware.php

<?php

namespace App\Http\Middleware;

use Closure;


class OwnerMiddleware
{
    public function handle($request, Closure $next,$role)
    {

        if(!$request->user()->hasRole($role)) {
            return redirect('/');
        }

        return $next($request);
    }
}

【问题讨论】:

  • 该错误似乎表明存在问题。所以在调用点找出为什么它是一个整数并从那里向后工作
  • 您的代码中有多个-&gt;toArray() 实例。哪个是抛出错误?乍一看,我认为它们中的任何一个都不会(它们都应该是Collection 的实例,它具有-&gt;toArray() 函数)。另外,请注意命名; public function role() 建议它返回一个 Role 实例,但它是一个belongsToMany(),它返回多个 Role 实例,所以它应该是复数@987654331 @.
  • 他报错 public function hasRole($check)
  • @QIPS, $this-&gt;role 必须是一个集合(不是整数),除非您在users 表中有role 列或role 模型中有role 属性。跨度>
  • 怎么全部写出来,不难就写代码

标签: php arrays laravel


【解决方案1】:

您在数据库中有role 列。它保留对您的role 关系集合的访问。您应该删除它或将role() 关系重命名为roles()。此外,belongsToMany 意味着用户可以拥有多个角色。

另外,我要注意的是集合有自己的方法in_array => containsarray_pluck =&gt; pluck。你可以这样优化你的代码:

public function roles()
{
    return $this->belongsToMany(Role::class, 'user_role');
}

public function isEmloyee(){
    return $this->roles->isNotEmpty();
}

public function hasRole($name){
    return $this->roles->pluck('name')->contains($name);
}

public function makeEmployee($name){
    $role = Role::where('name', $name)->first();
    if($role){
        $this->role()->attach($role->id);
    }
}

【讨论】:

猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 2017-12-25
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 2018-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多