2016-12-08 59 views
1

我在Laravel是新的自定义中间件文件。我正在开发一个应用程序,从现在开始,我只是使用laravel auth即(php artisan make:auth)。呼叫模型功能到Laravel 5.2

我的要求是拉的数据从一个表即“管理”到我的自定义中间件的loggedIn用户,但我无法调用它在我的模型即“管理”文件中定义的功能。

模型文件: - 应用程序\ admin.php的

<?php 
namespace App; 
use Illuminate\Foundation\Auth\User as Authenticatable; 
class Admin extends Authenticatable 
{ 
    /** 
    * The attributes that are mass assignable. 
    * 
    * @var array 
    */ 
    protected $fillable = [ 
     'name', 'email', 'password', 
    ]; 
    /** 
    * The attributes that should be hidden for arrays. 
    * 
    * @var array 
    */ 
    protected $hidden = [ 
     'password', 'remember_token', 
    ]; 
    public function roles() 
    { 
     return $this->belongsToMany('App\Role', 'admin_role', 'admin_id', 'role_id'); 
    } 
    public function hasAnyRole($roles) 
    { 
     if (is_array($roles)) { 
      foreach ($roles as $role) { 
       if ($this->hasRole($role)) { 
        return true; 
       } 
      } 
     } else { 
      if ($this->hasRole($roles)) { 
       return true; 
      } 
     } 
     return false; 
    } 

    public function hasRole($role) 
    { 
     if ($this->roles()->where('name', $role)->first()) { 
      return true; 
     } 
     return false; 
    } 
    public function myfunction($val) 
    { 
     echo "===>".$val; exit ; 
    } 
} 

中间件: - 打开应用程序\ HTTP \中间件\ CheckRole.php

<?php 
namespace App\Http\Middleware; 
use Closure; 

class CheckRole 
{ 
    /** 
    * Handle an incoming request. 
    * 
    * @param \Illuminate\Http\Request $request 
    * @param \Closure $next 
    * @return mixed 
    */ 
    public function handle($request, Closure $next) 
    { 

     $request->admin->myfunction('customvalue'); 
     exit ; 
    } 
} 

我需要调用函数,即 “MyFunction的”,这在Admin模型中定义为Checkrole.php中间件。

感谢

回答

0

尝试

auth()->user()->myfunction(); 

从中间件。 (我假设你在这一点上经过认证的用户)

+0

您好,感谢您的答复,但遗憾的是它不工作。我得到“调用一个非对象的成员函数myfunction()”错误,并且我已经编辑了我的问题,请您再次查看? – Abhishek

+0

你确定你是作为用户进行身份验证吗? dd(auth() - > check());在中间件中做? – pseudoanime

+0

它返回“假” – Abhishek