Laravel 5.5传递变量到子控制器返回总是null?

Laravel 5.5传递变量到子控制器返回总是null?

问题描述:

I have a main controller CmsController, wich is extended to default laravel controller:

use App\Http\Controllers\Controller;
class CmsController extends Controller
{
    protected $web = null;

    public function __construct(Request $request)
    {
        $this->web = Web::domain($request->domain)->first();
    }
}

Now, in this controller I want to call $this->web

use App\Http\Controllers\Web\PageController;
class PageController extends CmsController
{
    public function getPage(Request $request)
    {
        dd($this->web); // returns always null
    }
}

The data that should be returned is 100% correct, reqest params are also there...

Can someone give me a idea, what I did wrong here?

我有一个主控制器CmsController,它扩展到默认的laravel控制器: p> 使用App \ Http \ Controllers \ Controller; class CmsController扩展Controller { protected $ web = null; public function __construct(Request $ request) { $ this- > web = Web :: domain($ request-> domain) - > first(); } } code> pre>

现在,在此 controller我想调用 $ this-> web code> p>

 使用App \ Http \ Controllers \ Web \ PageController; 
class PageController扩展CmsController 
  {
公共函数getPage(请求$请求)
 {
 dd($ this-> web);  //返回始终为null 
} 
} 
  code>  pre> 
 
 

应返回的数据是100%正确,reqest params也在那里...... p >

有人可以给我一个想法吗,我在这里做错了什么? p> div>

I think you need to execute parent constructor:

class PageController extends CmsController
{
    public function __construct()
    {
         parent::__construct();
         ....
    }
}

Because you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet, and even if you did the dd($this->web); in the CmsController construct you will get null So you can do it like this :

use App\Http\Controllers\Controller;
class CmsController extends Controller
{
    protected $web = null;

    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $this->web = Web::domain($request->domain)->first();
            return $next($request);
        });
    }
}

You are extending CmsController and using PageController thats why ,

 use App\Http\Controllers\Web\CmsController;

 class PageController extends CmsController
 {
     public function getPage(Request $request)
     {
       dd($this->web); // returns always null
     }
 }

I have changed,

use App\Http\Controllers\Web\PageController;

to this,

use App\Http\Controllers\Web\CmsController;