为什么我没有在Laravel中的扩展构造函数中看到结果

时间:2018-01-05 14:31:59

标签: php laravel constructor middleware

我有几个类从抽象类扩展而来 和类MenuController从SiteAdminController扩展 我需要调用MenuController并接收经过身份验证的用户ID

<?php

namespace App\Http\Controllers\SiteAdmin;

use App\Http\Categories;
use Illuminate\Http\Request;
use Gate;
use App\Category;
use App\Http\Controllers\MenuController;
use App\Site_categories;
use Auth;

class SiteAdminController extends \App\Http\SiteEntity implements Categories
{      
    protected $host;
    public $user;

    public function __construct()
    {
        parent::__construct();
        $this->middleware('auth:admin');
    }

    protected function menu() {
        return $data_nav['menu'] = MenuController::index('admin_categories');
    }

其他一个扩展自SiteAdminCntroller

<?php
namespace App\Http\Controllers\SiteAdmin;

use Illuminate\Http\Request;
use Gate;
use Auth;
use App\Category;


class MenuController extends SiteAdminController
{
    public $category_menu;
    public $user_categories;
    public $user;

    public function __construct(Auth $auth)
    {    
         //parent::__construct();
         $this->user_categories=$this->CategoriesMenu();
         $this->user=$auth::guard('admin')->user()->id;
         dd($this->user);
         //dd($this->user_categories);
    }

我认为MenuController中的构造函数是在SiteAdminController中运行的middlware 这就是为什么我有这样的错误 http://prntscr.com/hwfifx 请解释我从dd()函数中查看结果有什么用? 我甚至试图打电话给parent::__construct,但没有帮助

2 个答案:

答案 0 :(得分:0)

首先检查班级是否看到另一个必须用。扩展的类。

然后尝试以下方法(仅作为示例):

class ConceptController extends \SiteAdminController {

public function __construct(SiteAdminController $siteAdmin) {

     parent::__construct($siteAdmin);

    }
}

答案 1 :(得分:0)

构造函数中的代码在中间件之前运行是正确的:https://github.com/laravel/framework/issues/15072

解决此问题的最简单方法是在控制器中使用middleware方法:

<强> MenuController

public function __construct()
{
    parent::__construct();

    $this->middleware(function () {
        $this->user_categories = $this->CategoriesMenu();
        $this->user = auth()->guard('admin')->user()->id;
    });
}