Php 对整数调用成员函数toArray()

Php 对整数调用成员函数toArray(),php,arrays,laravel,Php,Arrays,Laravel,User.php Role.php ownermidware.php 您在数据库中有角色列。它保留对角色关系集合的访问。您应该将其删除或重命名角色关系,例如将其重命名为角色。此外,归属意味着用户可以有许多角色 此外,我想指出,集合在_array=>contains、array_pull=>pull中有自己的方法。您可以这样优化代码: public function roles() { return $this->belongsToMany(Role::class, 'user_ro

User.php

Role.php

ownermidware.php

您在数据库中有角色列。它保留对角色关系集合的访问。您应该将其删除或重命名角色关系,例如将其重命名为角色。此外,归属意味着用户可以有许多角色

此外,我想指出,集合在_array=>contains、array_pull=>pull中有自己的方法。您可以这样优化代码:

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

这个错误似乎表明了这个问题。因此,找出为什么它在调用站点是一个整数,并从那里向后工作。您的代码中有许多->toArray的实例。哪一个抛出了错误?乍一看,我不认为它们中的任何一个都应该是集合的实例,集合具有->toArray函数。另外,注意命名;public function role表示它返回一个角色实例,但它是一个belongTomany,它返回多个角色实例,因此它应该是多个public function role。他给出了一个错误public function hasRole$check@QIPS,$this->role必须始终是集合而不是整数,除非在用户表中有role列或在用户模型中有role属性。如何编写所有这些,如果不困难,请用英语编写答案,如下所示:
class Role extends Model
{

   public function users()
   {

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

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