Laravel:未定义的属性

时间:2017-01-28 14:02:51

标签: php database laravel laravel-5.3

我有一个laravel项目,我开始编写管理方面的事情。我创建了一个中间件来检查他们的government_id>如果不是,则将它们重定向到被拒绝的页面。

中间件:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use View;
use App\Database\Website\Roleplay\GovernmentRole;

class AdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::guest() || Auth::user()->roleplay->government_id == 0)
        {
            return redirect("denied");
        }

        if (Auth::check())
        {
            View::share('myGovernmentRole', GovernmentRole::where('id', Auth::user()->roleplay->government_id)->get());
        }

        return $next($request);
    }
}

现在我问的问题是这个。

Undefined property: Illuminate\Database\Eloquent\Collection::$government_type

如您所见,我赞同观点:

View::share('myGovernmentRole', GovernmentRole::where('id', Auth::user()->roleplay->government_id)->get());

在我看来,我这样做:

@if ($myGovernmentRole->government_type == 'junior_ministers'
                    || $myGovernmentRole->government_type == 'senior_ministers'
                    || $myGovernmentRole->government_type == 'higher_government'
                    || $myGovernmentRole->government_type == 'royalty')
                        <li class="dropdown">
                            <a href="#" clas="dsropdown-toggle profile-image" data-toggle="dropdown">
                                <i class="fa fa-user"></i> &nbsp;JuniorCP <b class="caret"></b></a>
                            <ul class="dropdown-menu">
                                <li><a href="/business/overview"><i class="fa fa-briefcase"></i> &nbsp;Business</a></li>
                            </ul>
                        </li>
                    @endif

似乎在尝试获取government_type列时会发生这种情况,但我不知道为什么,我认为你可以这样做 - &gt;列上一个集合并获取列,我错了吗?

任何可以帮助感谢的人。使用Laravel 5.3

1 个答案:

答案 0 :(得分:0)

只需将View :: share命令放在App \ Providers \ AppServiceProvider.php文件的boot()方法中(注意将get()更改为first())。

如果guest或者governmentment_id为0,则此中间件将重定向。如果有,则不需要第二个...