【问题标题】:Call model function into custom middleware file in Laravel 5.2在 Laravel 5.2 中将模型函数调用到自定义中间件文件中
【发布时间】:2017-04-24 06:47:35
【问题描述】:

我是 Laravel 的新手。到目前为止,我正在从头开始开发一个应用程序,我只使用了 laravel auth,即(php artisan make:auth)。

我的要求是将登录用户的数据从表(即“admin”)中提取到我的自定义中间件中,但我无法调用在我的模型中定义的函数,即“Admin”文件。

模型文件:- app\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 ;
    }
}

中间件文件:- app\Http\Middleware\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 ; 
    }
}

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

谢谢

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    试试

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

    来自中间件。 (我假设您此时有一个经过身份验证的用户)

    【讨论】:

    • 您好,感谢您的回复,但不幸的是它不起作用。我收到“Call to a member function myfunction() on a non-object”错误,我已经编辑了我的问题,您能再检查一遍吗?
    • 您确定您已通过用户身份验证吗? dd(auth()->check()) 是做什么的;在中间件中做什么?
    • 返回“假”
    • 表示用户未登录。我确实提到该功能仅适用于经过身份验证的用户。
    • 我对 admin 和 frontend 都使用 auth,对于管理部分我有“admins”表,对于前端我有“users”表。而且我可以轻松地为两者分别登录并且工作正常。但不知道为什么我在调试后收到“错误”消息。
    猜你喜欢
    • 2017-02-12
    • 1970-01-01
    • 2016-06-26
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    相关资源
    最近更新 更多