2016-12-08 62 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